<template>
  <div v-loading="loading">
    <el-form
      ref="ruleForm"
      :model="ruleForm"
      status-icon
      :size="'mini'"
      :rules="rulesThis"
      label-width="115px"
      style="width: 100%"
      class="demo-ruleForm"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="退货总数量" prop="return_num">
            <el-input
              disabled
              v-model="ruleForm.return_num"
              placeholder="退货总数量"
              maxlength="10"
            ></el-input>
          </el-form-item>
          <el-form-item label="可销售数量" prop="normal">
            <el-input
              :disabled="!(status === '1' && ppowers.some((i) => i == '1'))"
              v-model="ruleForm.normal"
              placeholder="可销售数量"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="其他备注" prop="remark">
            <el-input
              :disabled="!(status === '1' && ppowers.some((i) => i == '1'))"
              type="textarea"
              maxlength="250"
              :rows="3"
              show-word-limit
              placeholder="请填写备注"
              v-model="ruleForm.remark"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="status === '1' && ppowers.some((i) => i == '1')">
          <el-form-item label="异常情况记录" :size="'mini'">
            <el-form
              :model="ruleForm"
              :rules="tableFormThis"
              ref="ruleForm"
              :size="'mini'"
              class="demo-tableForm product_go"
            >
              <el-table :data="ruleForm.product_go" border :size="'mini'" row-key="key">
                <el-table-column label="异常数量" prop="error_num" />
                <el-table-column label="异常原因" prop="error_code_name" />
                <el-table-column label="异常备注" prop="error_remark" />
                <el-table-column
                  fixed="right"
                  label="操作"
                  width="80"
                  v-if="status === '1' && ppowers.some((i) => i == '1')"
                >
                  <template slot="header" slot-scope="scope">
                    <!-- v-if="status == '1' || status == '0'" -->
                    <span>操作</span>
                    <el-tooltip
                      class="fr"
                      style="margin: 3px 0 0 0"
                      effect="dark"
                      content="添加"
                      placement="top"
                    >
                      <i
                        class="el-icon-circle-plus-outline tb-icon"
                        style="color: #6954f0"
                        @click="openModal(-1)"
                      ></i>
                    </el-tooltip>
                  </template>
                  <!-- v-if="status == '1' || status == '0'" -->
                  <template slot-scope="scope">
                    <el-tooltip
                      effect="dark"
                      content="编辑"
                      v-if="!scope.row.edit"
                      placement="top"
                    >
                      <i
                        class="el-icon-edit tb-icon"
                        @click="openModal(scope.$index)"
                      ></i>
                    </el-tooltip>

                    <el-tooltip
                      v-if="scope.row.edit"
                      effect="dark"
                      content="重置"
                      placement="top"
                    >
                      <i
                        class="el-icon-delete tb-icon"
                        @click="deleteRow(scope.$index, ruleForm.product_go)"
                      ></i>
                    </el-tooltip>
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
          </el-form-item>
        </el-col>
        <el-col
          :span="24"
          style="text-align: right; margin: -5px 0 20px 0"
          v-if="status === '1' && ppowers.some((i) => i == '1')"
        >
          <el-button type="primary" class="fr" :size="'mini'" @click="submitForm"
            >保 存
          </el-button>
        </el-col>
      </el-row>
      <abnormal-condition-modal
        :index="index"
        :sitem="s_item"
        :show-model="showModel"
        @refresh="handleValue"
        @cancel="showModel = false"
      />
    </el-form>
  </div>
</template>
<script>
import asyncRequest from "@/apis/service/sellOut/returnOrder";
import resToken from "@/mixins/resToken";
import { isnumber } from "@/utils/validate";
import abnormalConditionModal from "@/components/abnormal-condition-modal";
export default {
  name: "zxAfterSaleOrderDetail",
  props: ["id", "showModelThis", "newTime", "sitem"],
  mixins: [resToken],
  components: { abnormalConditionModal },
  data() {
    const validatenumbers = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("数量不能为空！"));
      } else {
        if (!isnumber(value)) {
          callback(new Error("数量格式不正确！"));
        } else {
          callback();
        }
      }
    };
    return {
      arr: [],
      s_item: null,
      sitemGetNumber: "", //详情总收货量
      isShow: false, //用于情况1
      returnNO: "", //退货编号
      ruleForm: {
        return_num: "", //收货总数量
        normal: "", //可销售数量
        remark: "", //其他备注
        product_go: [], //表格参数
      },

      btn_code: "",
      index: "",
      options: [],
      edit: false, //默认不能提交
      totalNumber: 0, //全局保存数量
      loading: false,
      status: "", //存储详情接口返的状态
      showModel: null,

      rulesThis: this.rules,
      // 验证规则
      rules: {
        return_num: [
          {
            required: true,
            trigger: "blur",
            validator: validatenumbers,
          },
        ],
        normal: [
          {
            required: true,
            trigger: "blur",
            validator: validatenumbers,
          },
        ],
        remark: [
          {
            required: true,
            trigger: "blur",
            message: "请填写备注信息",
          },
        ],
      },
    };
  },
  computed: {
    ppowers() {
      const tran =
        this.$store.getters.roleProcess.find((i) => i.process_type === "CKTHD") || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
  },

  mounted() {
    console.log("mounted----------");
    this.initForm();
  },
  watch: {
    newTime: function (val) {
      if (val) {
        console.log("newTime----------");
        this.initForm();
      }
    },
  },
  methods: {
    async initForm() {
      this.loading = true;
      this.rulesThis = this.rules;
      this.ruleForm = {
        return_num: "", //收货总数量
        normal: "", //可销售数量
        remark: "", //其他备注
        product_go: [], //表格参数
      };
      await this.getresultlist();
      await this.resetForm();
      this.loading = false;
    },

    async resetForm() {
      // 重置
      console.log("11111" + this.newTime);

      await this.$nextTick(() => {
        console.log(this.$refs.ruleForm);

        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          console.log("11111" + this.newTime);
          this.status = "";
          this.arr = [];
          console.log(this.sitem);
          let { child, status, normal_num, remark, return_num } = this.sitem;
          this.status = status;
          if (child) {
            this.arr = child && child.length > 0 ? JSON.parse(JSON.stringify(child)) : [];
            this.arr.forEach((v) => {
              v.is_del = "0";
              v.error_code_name = v.error_msg;
            });
          }
          this.ruleForm = {
            return_num: return_num || "",
            normal: normal_num || "", //可销售数量
            remark: remark, //其他备注
            product_go: this.arr, //表格参数this.arr
          };
        }
      });
    },

    async submitForm() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (this.loading) {
            return;
          }
          this.loading = true;

          let model = JSON.parse(JSON.stringify(this.ruleForm));
          let list = JSON.parse(JSON.stringify(this.arr));
          let { return_num, normal, product_go, remark } = model;
          let errorT = 0;
          if (product_go && product_go.length > 0) {
            product_go.forEach((v) => {
              errorT += parseInt(v.error_num);
            });
          }

          if (parseInt(normal) + errorT !== parseInt(return_num)) {
            this.$message.warning("可销售数量+异常总数量不等于退货总数量！");
            this.loading = false;
            return;
          }
          product_go.forEach((x) => {
            let index = list.findIndex((y) => x.id === y.id);
            if (index !== -1) {
              list.splice(index, 1);
            }
          });
          list.forEach((v) => {
            v.is_del = "1";
          });
          let item = {
            thNo: this.sitem.thNo,
            normal,
            remark,
            errorlist: [].concat(product_go).concat(list),
          };

          const res = await asyncRequest.returnCheck(item);
          this.loading = false;
          if (res && res.code === 0) {
            this.$notify.success({
              title: res.message,
              message: "",
            });
            this.$emit("refresh");
          } else if (res && res.code >= 100 && res.code <= 104) {
            await this.logout();
          } else {
            this.$message.warning(res.message);
          }
        }
      });
    },
    // 获取异常原因下拉列表
    async getresultlist() {
      const res = await asyncRequest.resultlist({
        page: 1,
        size: 100,
        type: "1",
        status: "3",
      });
      if (res && res.code === 0 && res.data) {
        const { list } = res.data;
        this.options = list;
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(res.message);
      }
    },

    // 删除行操作
    deleteRow(index, rows) {
      if (this.id !== "add" && rows[index].id) {
        this.delList.push(rows[index]);
      }
      rows.splice(index, 1);
      this.$refs.ruleForm.validateField("product_go");
    },
    openModal(index) {
      this.s_item =
        index === -1 ? {} : JSON.parse(JSON.stringify(this.ruleForm.product_go[index]));
      this.index = index;
      this.showModel = true;
    },
    // 获取弹窗的值
    handleValue(e) {
      const { index, item } = e;
      if (index === -1) {
        this.ruleForm.product_go.push(JSON.parse(JSON.stringify(item)));
      } else {
        const { error_num, error_code, error_remark, error_code_name, id } = JSON.parse(
          JSON.stringify(item)
        );
        this.ruleForm.product_go[index].id = id;
        this.ruleForm.product_go[index].error_num = error_num;
        this.ruleForm.product_go[index].error_code = error_code;
        this.ruleForm.product_go[index].error_remark = error_remark;
        this.ruleForm.product_go[index].error_code_name = error_code_name;
      }
      this.$refs.ruleForm.validateField("product_go");
    },
  },
};
</script>

<style lang="scss" scoped></style>
