<template>
  <div>
    <el-form
      :model="ruleForm"
      :rules="rulesThis"
      status-icon
      ref="ruleForm"
      label-width="120px"
      class="demo-ruleForm"
    >
      <el-row>
        <!-- 商品名称 -->
        <el-col :span="24">
          <el-form-item label="商品名称" prop="goods_name">
            <el-input
              :disabled="ruleForm.status !== '0' && id != 'add'"
              v-model="ruleForm.goods_name"
              readonly="true"
              @focus="hand"
            ></el-input>
            <!-- <search-good-modal /> -->
          </el-form-item>
        </el-col>
        <!-- 采购数量 -->
        <el-col :span="24">
          <el-form-item label="采购数量" prop="goods_num">
            <el-input
              :disabled="ruleForm.status != '0' && id != 'add'"
              v-model="ruleForm.goods_num"
              placeholder="请输入内容"
              :size="searchSize"
            ></el-input>
          </el-form-item>
        </el-col>
        <!-- 最晚入库时间 -->
        <el-col :span="24">
          <el-form-item label="最晚入库时间" prop="last_go_stock">
            <el-date-picker
              :size="searchSize"
              v-model="ruleForm.last_go_stock"
              type="date"
              style="width: 100%"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期"
              :picker-options="pickerOptions"
              @change="selectTime"
              :disabled="ruleForm.status !== '0' && id != 'add'"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <!-- 供应商选择 -->
        <el-col :span="24">
          <el-form-item label="供应商名称" prop="supplier_code">
            <search-supplier
              :disabled="ruleForm.status !== '0' && id != 'add'"
              :value="ruleForm.supplier_code"
              :placeholder="'请选择供应商'"
              @searchChange="selectSupplier"
            />
          </el-form-item>
        </el-col>
        <!-- 仓库名称 -->
        <el-col :span="24">
          <el-form-item label="仓库名称" prop="stock_code">
            <search-stock
              :disabled="ruleForm.status !== '0' && id != 'add'"
              :value="ruleForm.stock_code"
              :isDetail="true"
              :placeholder="'请选择备库仓库'"
              :isRelation="true"
              :companyCode="companyCode"
              @searchChange="selectStock"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24" style="text-align: right">
          <el-button
            type="primary"
            @click="submitForm"
            v-if="id == 'add' || ruleForm.status == '0'"
            >保 存</el-button
          >
          <el-button
            type="primary"
            @click="statusConfirm('1', '发起审核流程')"
            v-if="
              id != 'add' && ruleForm.status != '1' && ruleForm.status != '2'
            "
            >发起备货申请
          </el-button>
          <el-button
            @click="statusConfirm('0', '取消审核流程')"
            plain
            v-if="ruleForm.status == '1' && id !== ''"
            >取消备货申请</el-button
          >
          <el-button
            v-if="id != 'add' && ruleForm.status != '2'"
            @click="statusConfirm('-1', '作废该条信息')"
            type="danger"
            plain
            >作废该条信息</el-button
          >
          <el-button
            @click="statusConfirm('2', '通过审核')"
            type="primary"
            v-if="ruleForm.status === '1'"
            >反馈备货信息</el-button
          >
        </el-col>
      </el-row>
    </el-form>
    <search-stock-good-modal
      :once="true"
      :show-model="showGoodsModel"
      @cancel="showGoodsModel = false"
      @searchChange="addGoodsRes"
    />
  </div>
</template>
   <script>
import resToken from "@/mixins/resToken";
import asyncRequest from "@/apis/service/purchaseIn/storeManage";
export default {
  name: "storeManage",
  props: ["id", "isDetail", "sitem"],
  mixins: [resToken],
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        },
      },
      // id: "",
      routerId: "",
      stockCode: "",
      companyCode: "",
      showGoodsModel: "", //打开新弹窗
      loading: false,
      title: "新建备货申请",

      ruleForm: {
        id: "", //保存路由来的id
        good_code: "",
        good_type_code: "",
        goods_name: "", //商品名称
        goods_num: "", //商品数量
        last_go_stock: "", //最晚入库时间
        supplier_code: [], //供应商名称
        stock_code: [],
        status: "", //当前状态
      },
      rulesThis: this.rules,
      rules: {
        //出入库规则
        goods_name: [
          {
            required: true,
            message: "商品名称不能为空",
            trigger: "blur",
          },
        ],
        goods_num: [
          {
            required: true,
            message: "请选择入库仓库",
            trigger: "blur",
          },
        ],
        last_go_stock: [
          {
            // type: "date",
            required: true,
            message: "请输入入库最晚时间",
            // trigger: "blur" ,
            trigger: ["blur", "change"],
          },
        ],
        supplier_code: [
          {
            type: "array",
            required: true,
            message: "请选择供应商",
            trigger: "change",
          },
        ],
        stock_code: [
          {
            type: "array",
            required: true,
            message: "请选择仓库",
            trigger: "change",
          },
        ],
      },
    };
  },
  mounted() {
    this.routerId = this.$route.query.id;
    this.searchList();
    this.initForm();
  },
  methods: {
    async initForm() {
      this.loading = true;
      // await this.getRole();
      if (this.id === "add") {
        this.rulesThis = this.rules;
        await this.resetForm();
      } else {
        if (this.isDetail) {
          this.rulesThis = {};
        } else {
          this.rulesThis = this.rules;
        }
        console.log(this.id);
        await this.resetForm();
        // await this.initData();
      }
      this.loading = false;
    },
    // 获取备库详情
    async searchList() {
      this.loading = true;
      const res = await asyncRequest.detail({ id: this.routerId });
      if (res && res.code === 0 && res.data) {
        let {
          good_code,
          good_name, //商品名
          good_num, //采购数量
          good_type_code, //商品属性code
          wsm_code, //仓库code
          lasttime, //最晚入库时间
          wsm_name, //仓库名
          status,
        } = res.data;
        this.ruleForm = {
          good_code,
          id: this.routerId,
          goods_name: good_name, //商品名
          goods_num: good_num, //采购数量
          last_go_stock: lasttime, //最晚入库时间
          good_type_code, //商品属性code
          wsm_code, //仓库code
          supplier_code: ["缺供应商"],
          stock_code: wsm_name.split(","), //仓库名
          status,
          // 缺少供应商名称和供应商code
        };
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.tableData = [];
      }
      this.loading = false;
    },
    // 选择仓库
    selectStock(e) {
      if (e && e.id) {
        this.ruleForm.stock_code = [e.code];
        this.stockCode = e.code;
      } else {
        this.ruleForm.stock_code = [];
        this.stockCode = "";
      }
      this.$refs.ruleForm.validateField("stock_code");
    },
    // 选择供应商
    selectSupplier(e) {
      if (e && e.id) {
        this.ruleForm.supplier_code = [e.code];
        this.companyCode = e.code;
      } else {
        this.ruleForm.supplier_code = [];
        this.companyCode = "";
        this.ruleForm.stock_code = [];
        this.stockCode = "";
      }
      this.$refs.ruleForm.validateField("supplier_code");
    },
    // 执行点击商品名称的抛出事件
    addGoodsRes(e) {
      let { good_code, type_code, good_name } = e[0];
      this.ruleForm.goods_name = good_name;
      this.ruleForm.good_type_code = type_code;
      this.ruleForm.good_code = good_code;
      this.$refs.ruleForm.validateField("goods_name");
    },
    hand() {
      this.showGoodsModel = true;
    },
    // 最晚入库时间选择
    selectTime(e) {
      this.ruleForm.last_go_stock = e;
    },
    closeModel() {
      console.log("closeModel!!");
      this.$emit("closeModel");
    },
    // 重置
    async resetForm() {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          this.ruleForm = {
            stock_code: [],
            supplier_code: [],
            good_code: "",
            good_type_code: "",
            goods_name: "", //商品名称
            goods_num: "", //商品数量
            last_go_stock: "", //最晚入库时间
            stock_in_rule: "", //入库仓库
          };
        }
      });
    },
    // 保存更改
    async submitForm() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          const {
            id, //申请单ID
            stock_code, //仓库编码
            good_code, //商品code
            good_type_code, //商品属性code
            last_go_stock, //最晚入库时间
            goods_num, //入库数量
          } = this.ruleForm;
          const model = {
            id,
            good_code: good_code || "",
            good_type_code: good_type_code || "",
            good_num: goods_num || "",
            wsm_code: stock_code.toString() || "",
            lastime: last_go_stock || "",
          };
          let res = {};
          if (this.id === "add") {
            delete model["id"];
            res = await asyncRequest.add(model);
          } else {
            res = await asyncRequest.update(model);
          }
          this.loading = false;
          if (res && res.code === 0) {
            const title = this.id === "add" ? "添加成功" : "修改成功";
            this.$notify.success({
              title,
              message: "",
            });
            this.$emit("closeModel");
            this.routeGoto("storeManage", {});
          } else if (res && res.code >= 100 && res.code <= 104) {
            await this.logout();
          } else {
            this.$message.warning(res.message);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    // 发起申请
    async statusConfirm(status, message) {
      await this.$confirm(`确定要${message}？`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          if (status === "-1") {
            await this.deleteById(message);
          } else {
            await this.setStatus(status, message);
          }
        })
        .catch(() => {
          console.log("取消");
        });
    },
    // 作废该条信息
    async deleteById(message) {
      const res = await asyncRequest.delete({ id: this.routerId });
      if (res && res.code === 0) {
        this.$notify.success({
          title: message + "成功！",
          message: "",
        });

        this.routeGoto("storeManage", {});
        this.searchList();
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(res.message);
      }
    },
    // 状态修改
    async setStatus(status, message) {
      let model = {
        id: this.routerId,
        remark: "",
        status: status,
      };
      const res = await asyncRequest.status(model);
      this.loading = false;
      if (res && res.code === 0) {
        this.$notify.success({
          title: message + "成功！",
          message: "",
        });
        this.searchList();
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(res.message);
      }
    },
  },
};
</script>
   