<template>
  <div>
    <el-form
      :model="ruleForm"
      :rules="rulesThis"
      status-icon
      ref="ruleForm"
      label-width="120px"
      class="demo-ruleForm"
    >
      <el-row>
        <el-col :span="type === '1' ? 12 : 24">
          <el-form-item label="商品分类" prop="goods_name">
            <good-class
              :value="ruleForm.goods_class"
              @handleChange="goods_class_change"
              :disabled="
                !(
                  id === 'add' ||
                  (status === '0' && powers.some((item) => item == '005'))
                )
              "
              :placeholder="'商品分类'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="type === '1' ? 12 : 24">
          <el-form-item label="商品名称" prop="goods_name">
            <el-input
              :disabled="
                !(
                  id === 'add' ||
                  (status === '0' && powers.some((item) => item == '005'))
                )
              "
              v-model="ruleForm.goods_name"
              readonly="true"
              :placeholder="'商品名称'"
              @focus="hand"
            ></el-input>
          </el-form-item>
        </el-col>
        <!-- 采购数量 -->
        <el-col :span="type === '1' ? 12 : 24">
          <el-form-item label="采购数量" prop="goods_num">
            <el-input
              :disabled="
                !(
                  id === 'add' ||
                  (status === '0' && powers.some((item) => item == '005'))
                )
              "
              v-model="ruleForm.goods_num"
              placeholder="采购数量"
            ></el-input>
          </el-form-item>
        </el-col>
        <!-- 最晚入库时间 -->
        <el-col :span="type === '1' ? 12 : 24">
          <el-form-item label="最晚入库时间" prop="last_go_stock">
            <el-date-picker
              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="
                !(
                  id === 'add' ||
                  (status === '0' && powers.some((item) => item == '005'))
                )
              "
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <!-- 供应商选择 -->
        <el-col :span="type === '1' ? 12 : 24">
          <el-form-item label="入库公司" prop="supplier_code">
            <search-supplier
              :disabled="
                !(
                  id === 'add' ||
                  (status === '0' && powers.some((item) => item == '005'))
                )
              "
              :value="ruleForm.supplier_code"
              :placeholder="'入库公司'"
              :names="''"
              @searchChange="selectSupplier"
            />
          </el-form-item>
        </el-col>
        <!-- 仓库名称 -->
        <el-col :span="type === '1' ? 12 : 24">
          <el-form-item label="入库仓库" prop="stock_code">
            <search-stock
              :disabled="!(id == 'add' || status === '0')"
              :value="ruleForm.stock_code"
              :placeholder="'入库仓库'"
              :isRelation="true"
              :names="''"
              :companyCode="companyCode"
              @searchChange="selectStock"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24" style="text-align: right">
          <el-button
            type="primary"
            @click="submitForm"
            :size="'mini'"
            v-if="
              id === 'add' ||
              (status == '0' && powers.some((item) => item == '005'))
            "
            >保 存
          </el-button>
        </el-col>
      </el-row>
    </el-form>
    <search-stock-good-modal
      :once="true"
      :cat_id="cat_id"
      :show-model="showGoodsModel"
      @cancel="showGoodsModel = false"
      @searchChange="addGoodsRes"
    />
  </div>
</template>
   <script>
import resToken from "@/mixins/resToken";
import asyncRequest from "@/apis/service/purchaseIn/storeManage";
import { isnumber } from "@/utils/validate";
import searchStockGoodModal from "@/components/search-stock-good-modal";
export default {
  name: "storeManage",
  props: ["id", "sitem", "newTime", "type"],
  mixins: [resToken],
  components: { searchStockGoodModal },
  computed: {
    powers() {
      let tran =
        this.$store.getters.btnList.find(
          (item) => item.menu_route == "storeManageFlow"
        ) || {};
      if (tran && tran.action && tran.action.length > 0) {
        return tran.action;
      } else {
        return [];
      }
    },
  },
  watch: {
    newTime: function (val) {
      if (val) {
        this.initForm();
      }
    },
  },
  data() {
    const validateWeight = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("不能为空!"));
      } else {
        if (!isnumber(value)) {
          callback(new Error("仅支持整数!"));
        } else {
          callback();
        }
      }
    };
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        },
      },
      status: "",
      cat_id: "",
      routerId: "",
      stockCode: "",
      companyCode: "",
      showGoodsModel: "",
      loading: false,
      ruleForm: {
        id: "",
        goods_class: [],
        good_code: "",
        good_type_code: "",
        goods_name: "",
        goods_num: "",
        last_go_stock: "",
        supplier_code: [],
        supplier_name: "",
        stock_code: [],
      },
      rulesThis: this.rules,
      rules: {
        goods_class: [
          {
            type: "array",
            required: true,
            message: "请选择商品分类",
            trigger: "change",
          },
        ],
        //出入库规则
        goods_name: [
          {
            required: true,
            message: "商品名称不能为空",
            trigger: "blur",
          },
        ],
        goods_num: [
          {
            required: true,
            validator: validateWeight,
            trigger: "blur",
          },
        ],
        last_go_stock: [
          {
            required: true,
            message: "请输入入库最晚时间",
            trigger: "change",
          },
        ],
        supplier_code: [
          {
            type: "array",
            required: true,
            message: "请选择供入库公司",
            trigger: "change",
          },
        ],
        stock_code: [
          {
            type: "array",
            required: true,
            message: "请选择入库仓库",
            trigger: "change",
          },
        ],
      },
    };
  },
  created() {
    this.initForm();
  },
  methods: {
    async initForm() {
      this.loading = true;
      this.status = this.sitem !== undefined ? this.sitem.status : "";

      if (this.id === "add") {
        this.status = "";
      }
      this.rulesThis = this.rules;
      await this.resetForm();
      this.loading = false;
    },
    goods_class_change(e) {
      this.ruleForm.goods_class = e;
      this.cat_id = e.length > 0 ? e[e.length - 1] : "";
      this.$refs.ruleForm.validateField("goods_class");
      this.ruleForm.good_type_code = "";
      this.ruleForm.goods_name = "";
      this.ruleForm.goods_num = "";
      this.$refs.ruleForm.validateField("good_type_code");
    },
    // 最晚入库时间选择
    selectTime(e) {
      this.ruleForm.expecttime = e;
    },
    // 选择仓库
    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() {
      if (this.ruleForm.goods_class.length === 0) {
        this.$message.warning("请选择商品分类！");
        return;
      }
      this.showGoodsModel = true;
    },
    // 最晚入库时间选择
    selectTime(e) {
      this.ruleForm.last_go_stock = e;
    },
    closeModel() {
      this.$emit("closeModel");
    },
    // 重置
    async resetForm() {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          if (this.sitem) {
            const {
              id,
              good_code,
              good_type_code,
              good_name, //商品名
              good_num, //采购数量
              lasttime, //最晚入库时间
              wsm_code, //仓库名
              status,
              wsm_supplier,
              wsm_supplierNo,
              can,
              // 缺供应商
            } = this.sitem;
            this.companyCode = wsm_supplierNo;

            this.cat_id = can.length > can ? e[e.length - 1] : "";
            let goods_class = [];
            can.forEach((v) => {
              goods_class.push(v.id);
            });
            this.ruleForm = {
              id,
              goods_class: goods_class,
              good_code,
              good_type_code,
              goods_name: good_name,
              goods_num: good_num,
              last_go_stock: lasttime,
              supplier_code: [],
              stock_code: wsm_code.split(","),
              companyCode: wsm_supplierNo,
              supplier_name: wsm_supplierNo.split(","),
              supplier_code: wsm_supplier.split(","),
              status,
            };
          }
        }
      });
    },
    // 保存更改
    async submitForm() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          let {
            id,
            good_code,
            good_type_code,
            goods_num,
            stock_code,
            last_go_stock,
          } = this.ruleForm;
          let model = {
            id: id,
            good_code,
            good_type_code,
            good_num: goods_num || "",
            wsm_code:
              this.id == "add" ? stock_code.toString() : 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);
          }
          if (res && res.code === 0) {
            const title = this.id === "add" ? "添加成功" : "修改成功";
            this.$notify.success({
              title,
              message: "",
            });
            this.$emit("refresh");
            this.$emit("closeModel");
          } else if (res && res.code >= 100 && res.code <= 104) {
            await this.logout();
          } else {
            this.$message.warning(res.message);
          }
          this.loading = false;
        } 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", {});
      } 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: "",
        });
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(res.message);
      }
    },
  },
};
</script>
   