<template>
  <div v-loading="loading">
    <el-row>
      <el-col :span="4">
        <el-form
          :model="ruleForm"
          :rules="rulesThis"
          status-icon
          :size="'mini'"
          ref="ruleForm"
          label-width="80px"
          class="demo-ruleForm"
        >
          <el-form-item label="发货总数">
            <el-input
              placeholder="发货总数"
              disabled
              v-model="ruleForm.send_num"
              maxlength="100"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="正常数量" prop="wsm_num">
            <digital-input
              :values="ruleForm.wsm_num"
              :placeholder="'正常数量'"
              :min="0"
              :disabled="!(status === '1' && ppowers.some((i) => i == '1'))"
              :max="ruleForm.send_num"
              :position="'right'"
              :precision="0"
              :size="'mini'"
              :controls="false"
              :append="''"
              @reschange="number_change($event, 'wsm_num')"
            />
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="20" style="padding: 0 0 0 10px">
        <wsm-in-order-error-model
          :showModel="showModel"
          :id="modelId"
          :sitem="modelitem"
          :allnum="modelAllnum"
          @refresh="errorModel"
          @cancel="showModel = false"
        />
        <el-form
          :model="tableForm"
          :rules="tableRules"
          ref="tableForm"
          class="demo-tableForm"
        >
          <el-table :data="tableForm.error_list" border :size="'mini'" row-key="key">
            <template v-for="(item, index) in columns">
              <el-table-column
                :prop="item.prop"
                show-overflow-tooltip
                :label="item.label"
                v-if="item.prop !== 'error_img'"
                :key="item.prop + index"
              />
              <el-table-column
                :prop="item.prop"
                :label="item.label"
                v-if="item.prop === 'error_img'"
                :key="item.prop + index"
                width="350px"
              >
                <template slot-scope="scope">
                  <ul class="el-table-column-error_img-ul clear">
                    <li
                      v-for="item in scope.row.error_img"
                      :key="item"
                      v-viewer
                      class="hover"
                    >
                      <img :src="item" alt="" />
                    </li>
                  </ul>
                </template>
              </el-table-column>
            </template>
            <el-table-column
              fixed="right"
              width="80"
              v-if="status === '1' && ppowers.some((i) => i == '1')"
            >
              <template slot="header" slot-scope="scope">
                <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="addError(-1)"
                  ></i>
                </el-tooltip>
              </template>
              <template slot-scope="scope">
                <el-tooltip effect="dark" content="编辑" placement="top">
                  <i class="el-icon-edit tb-icon" @click="addError(scope.$index)"></i>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </el-col>
      <el-col :span="24" style="text-align: right; padding: 10px 0">
        <el-button
          type="primary"
          :size="'mini'"
          v-if="status === '1' && ppowers.some((i) => i == '1')"
          @click="submitForm"
          >保 存
        </el-button>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import asyncRequest from "@/apis/service/purchaseIn/purchaseOrder";
import resToken from "@/mixins/resToken";
import { isnumber } from "@/utils/validate";
import wsmInOrderErrorModel from "./wsm-in-order-error-model";
export default {
  name: "wsmInOrderAdd",
  props: ["id", "sitem", "newTime", "modelSitem"],
  components: { wsmInOrderErrorModel },
  mixins: [resToken],
  computed: {
    powers() {
      const tran =
        this.$store.getters.btnList.find(
          (item) => item.menu_route == "wsmInOrderDetail"
        ) || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
    ppowers() {
      const tran =
        this.$store.getters.roleProcess.find((i) => i.process_type === "RKD") || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
  },
  data() {
    const validateWeight = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("不能为空!"));
      } else {
        if (!isnumber(value)) {
          callback(new Error("仅支持整数!"));
        } else {
          callback();
        }
      }
    };

    return {
      loading: true,
      rulesThis: this.rules,
      status: "",
      showModel: false,
      modelAllnum: "",
      modelitem: null,
      modelId: "",
      ruleForm: {
        wsm_num: "",
      },
      rules: {
        wsm_num: {
          required: true,
          validator: validateWeight,
          trigger: "blur",
        },
      },
      columns: [
        {
          prop: "num",
          label: "异常数量",
        },
        {
          prop: "error_msg",
          label: "异常原因",
        },
        {
          prop: "error_img",
          label: "异常图片",
        },
        {
          prop: "remark",
          label: "异常备注",
        },
      ],
      tableForm: {
        error_list: [],
      },
      tableRules: {},
    };
  },
  watch: {
    newTime: function (val) {
      if (val) {
        this.initForm();
      }
    },
  },
  mounted() {
    this.initForm();
  },
  methods: {
    async initForm() {
      this.loading = true;
      this.rulesThis = this.rules;
      await this.resetForm();
      this.loading = false;
    },
    errorModel(e) {
      if (e) {
        let index = e.index;
        if (index === -1) {
          this.tableForm.error_list.push(e);
        } else {
          this.$set(this.tableForm.error_list, index, e);
        }
      }
    },
    //初始化表单
    async resetForm() {
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          const { send_num, wsm_num, status } = this.sitem;
          this.status = status;
          this.ruleForm = {
            send_num: send_num || "",
            wsm_num: wsm_num || "",
          };
        }
        if (this.$refs.tableForm) {
          this.$refs.tableForm.resetFields();
          this.$refs.tableForm.clearValidate();

          const { checkinfo } = this.sitem;
          checkinfo.map((v) => {
            v.error_img = v.error_img.split(",");
          });
          this.tableForm = {
            error_list: checkinfo || [],
          };
        }
      });
    },
    async number_change(e, key) {
      this.ruleForm[key] = e + "" || "0";
      this.$refs.ruleForm.validateField(key);
    },
    addError(index) {
      this.modelAllnum = "2";
      this.modelitem = index === -1 ? {} : this.tableForm.error_list[index];
      this.modelId = index;
      this.showModel = true;
    },

    // 保存更改
    async submitForm() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (this.loading) {
            return;
          }
          this.loading = true;
          const item = JSON.parse(JSON.stringify(this.ruleForm));
          let snum = parseInt(item.send_num),
            wnum = parseInt(item.wsm_num),
            errornum = 0,
            list = [];

          if (snum === wnum && this.tableForm.error_list.length > 0) {
            this.$message.warning("正常数量与发货数量一致，无需填写异常原因！");
            this.loading = false;
            return;
          }
          this.tableForm.error_list.forEach((v) => {
            errornum += parseInt(v.num);
            let model = {
              num: v.num,
              error_code: v.error_code,
              error_img: v.error_img.join(","),
              remark: v.remark,
            };
            list.push(model);
          });
          console.log(errornum, wnum, snum);

          if (errornum + wnum !== snum) {
            this.$message.warning("异常数量总数与发货总数不一致！");
            this.loading = false;
            return;
          }
          let pitem = {
            wsm_in_code: this.id,
            order_num: wnum + "",
            error_list: list,
          };
          const res = await asyncRequest.orderincheck(pitem);
          this.loading = false;
          if (res && res.code === 0) {
            this.$notify.success({
              title: "添加成功",
              message: "",
            });
            this.$emit("refresh"); //抛出事件给详情页。
          } 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;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.stockInDetail {
  .el-table-column-error_img-ul {
    position: relative;
    box-sizing: border-box;
    li {
      float: left;
      // border: 1px solid #dfe6ec;
      margin: 0px 2px 0 0px;
      box-sizing: border-box;
      img {
        display: inline-block;
        box-sizing: border-box;
        width: 20px;
        vertical-align: top;
        height: 20px;
        &:hover {
          cursor: pointer;
        }
      }
    }
  }
}
</style>
