<template>
  <el-row class="addForm">
    <el-col :span="24">
      <el-form
        :model="tableForm"
        :rules="tableFormThis"
        ref="tableForm"
        :size="'mini'"
        class="demo-tableForm product_go"
      >
        <el-table :data="tableForm.product_go" 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.type === 'text' && item.show && item.prop !== 'error_code'"
              :width="item.width"
              :min-width="item.minWidth"
              :key="item.prop + index"
            />
            <el-table-column
              :prop="item.prop"
              :label="item.label"
              v-else-if="item.type === 'text' && item.show && item.prop === 'error_code'"
              :width="item.width"
              :min-width="item.minWidth"
              :key="item.prop + index"
            >
              <template slot-scope="scope">
                <span class="spscope">{{ scope.row.error_msg }}</span>
              </template>
            </el-table-column>
            <el-table-column
              :prop="item.prop"
              :label="item.label"
              v-else-if="item.type !== 'text' && item.show"
              :width="item.width"
              :min-width="item.minWidth"
              :key="item.prop + index"
            >
              <template slot-scope="scope">
                <el-form-item
                  :prop="'product_go.' + scope.$index + '.' + item.prop"
                  :rules="scope.row.edit ? tableFormThis[item.prop] : {}"
                  :size="'mini'"
                >
                  <el-input
                    v-if="scope.row.edit === true && item.type === 'input'"
                    :size="'mini'"
                    maxlength="250"
                    clearable
                    v-model="scope.row[item.prop]"
                  />
                  <el-select
                    v-model="scope.row[item.prop]"
                    v-if="scope.row.edit === true && item.type === 'select'"
                    style="width: 100%"
                    clearable
                    placeholder="异常原因"
                    @change="elSelectChange($event, scope.$index)"
                  >
                    <el-option
                      v-for="item in options"
                      :key="item.result_code"
                      :label="item.result"
                      :value="item.result_code"
                      :disabled="item.status === '0'"
                    >
                    </el-option>
                  </el-select>
                  <span v-if="!scope.row.edit" class="spscope">{{
                    item.type === "select" ? scope.row.error_msg : scope.row[item.prop]
                  }}</span>
                </el-form-item>
              </template>
            </el-table-column>
          </template>

          <el-table-column
            fixed="right"
            v-if="
              (status == '3' && ppowers.some((i) => i == '3')) ||
              (status == '4' && ppowers.some((i) => i == '4'))
            "
            label="操作"
            width="80"
          >
            <template slot-scope="scope">
              <el-tooltip
                effect="dark"
                content="编辑"
                v-if="!scope.row.edit"
                placement="top"
              >
                <i class="el-icon-edit tb-icon" @click="editRow(scope.$index)"></i>
              </el-tooltip>

              <el-tooltip
                effect="dark"
                content="保存"
                v-if="scope.row.edit"
                placement="top"
              >
                <i
                  class="el-icon-circle-check tb-icon"
                  @click="checkRow(scope.$index)"
                ></i>
              </el-tooltip>

              <el-tooltip effect="dark" content="重置" placement="top">
                <i
                  class="el-icon-refresh-left tb-icon"
                  @click="resetRow(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 0 0">
      <el-button
        type="primary"
        :size="'mini'"
        @click="submitForm"
        v-if="
          (status == '3' && ppowers.some((i) => i == '3')) ||
          (status == '4' && ppowers.some((i) => i == '4'))
        "
        >保 存
      </el-button>
    </el-col>
  </el-row>
</template>
<script>
import asyncRequest from "@/apis/service/stock/allot/detail";
import resToken from "@/mixins/resToken";
import { isnumber } from "@/utils/validate";
import config from "./columns"; //表格列参数
export default {
  name: "allot",
  props: ["id", "sitem", "newTime"],
  mixins: [resToken],
  computed: {
    ppowers() {
      const tran =
        this.$store.getters.roleProcess.find((i) => i.process_type === "DBD") || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
  },
  data() {
    return {
      options: [],
      status: "",
      loading: false,
      tableForm: {
        product_go: [], //出库商品
      },
      tableFormThis: config.tableFormThis,
      columns: [],
    };
  },
  watch: {
    newTime: function (val) {
      if (val) {
        this.initForm();
      }
    },
  },
  mounted() {
    this.initForm();
  },
  methods: {
    async initForm() {
      this.loading = true;
      this.columns = [];
      await this.getresultlist();
      await this.resetForm();
      this.loading = false;
    },
    async getresultlist() {
      const res = await asyncRequest.resultlist({
        page: 1,
        size: 100,
        type: "1",
        status: "",
      });
      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);
      }
    },
    async resetForm() {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.tableForm) {
          this.$refs.tableForm.resetFields();
          this.$refs.tableForm.clearValidate();
          const { item, status } = this.sitem;
          this.status = status;
          let columnsList = JSON.parse(JSON.stringify(config.columns));
          columnsList.forEach((v1) => {
            if (this.status == "5" || this.status == "4") {
              v1.show = true;
            }
            if (this.status == "4" && v1.prop === "stock_num") {
              v1.type = "input";
              v1.width = "150px";
            }
            if (this.status == "3") {
              if (v1.prop === "error_remark" || v1.prop === "error_num") {
                v1.show = true;
                v1.width = "150px";
                v1.type = "input";
              }
              if (v1.prop === "error_code") {
                v1.show = true;
                v1.width = "150px";
                v1.type = "select";
              }
            }
            this.columns.push(v1);
          });
          this.tableForm.product_go = [];
          let list = JSON.parse(JSON.stringify(item));
          //  item || []; //出库商品
          list.forEach((v) => {
            v.usable_stock = v.usable_num;
            v.type_code = v.good_type_code;
            v.error_num = v.error_num || "0";
            v.error_code = v.error_code || "";
            v.error_msg = v.error_msg || "";
            v.error_remark = v.error_remark || "";
            v.stock_num = v.stock_num || "0";
            v.edit = false;
            this.tableForm.product_go.push(v);
          });
        }
      });
    },

    async submitForm() {
      if (this.loading) {
        return;
      }
      this.loading = true;
      let index = -1,
        good = [];
      this.tableForm.product_go.forEach((v, i) => {
        if (v.edit && index === -1) {
          index = i;
        }
      });
      if (index !== -1) {
        this.$message.warning("当前已有商品正在编辑！");
        this.loading = false;
        return;
      }

      good = this.getGoodList();
      const model = {
        allot_code: this.sitem.allot_code,
        good: good,
      };
      let res = {};
      if (this.status == "3") {
        res = await asyncRequest.allotgetin(model);
      } else {
        res = await asyncRequest.allotvesio(model);
      }

      this.loading = false;
      if (res && res.code === 0) {
        this.$notify.success({
          title:
            this.status == "3" ? "入库方验货结果提交成功!" : "入库方验货审核结果提交成功",
          message: "",
        });

        this.$emit("refresh");
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(res.message);
      }
    },
    //提交表单前 商品信息list 汇总
    getGoodList() {
      let oldList = JSON.parse(JSON.stringify(this.tableForm.product_go)),
        resList = [];
      oldList.forEach((v1) => {
        let goodModel = {
          id: v1.id,
          good_code: v1.type_code,
          usable_num: v1.usable_stock,
          error_num: v1.error_num,
          error_remark: v1.error_remark,
          error_code: v1.error_code,
        };
        if (this.status === "4") {
          goodModel.stock_num = v1.stock_num;
        }

        resList.push(goodModel);
      });
      return resList;
    },
    // 重置行操作
    resetRow(index) {
      if (this.status === "3") {
        this.tableForm.product_go[index].error_num = "0";
        this.tableForm.product_go[index].error_code = "";
        this.tableForm.product_go[index].error_msg = "";
        this.tableForm.product_go[index].error_remark = "";
      } else {
        this.tableForm.product_go[index].stock_num = "0";
      }
    },
    //异常原因筛选
    elSelectChange(e, index) {
      let oindex = this.options.findIndex((v) => v.result_code === e);
      this.tableForm.product_go[index].error_msg =
        oindex !== -1 ? this.options[oindex].result : "";
    },
    //保存某一行
    checkRow(rowIndex) {
      const {
        allot_num,
        error_num,
        error_code,
        error_remark,
        stock_num,
      } = this.tableForm.product_go[rowIndex];
      if (this.status === "3") {
        if (!isnumber(error_num + "") || error_num === "") {
          this.$message.warning("异常数量必须为整数！");
          return;
        }
        if (parseInt(error_num + "") > parseInt(allot_num + "")) {
          this.$message.warning("异常数量不大于调拨总数量！");
          return;
        }
        if (parseInt(error_num + "") > 0 && error_code === "") {
          this.$message.warning("请选择异常原因！");
          return;
        }
        if (parseInt(error_num + "") > 0 && error_remark === "") {
          this.$message.warning("请输入异常备注！");
          return;
        }
        if (parseInt(error_num + "") === 0 && error_code !== "") {
          this.$message.warning("异常数量为零，不用选择异常原因！");
          return;
        }
        if (parseInt(error_num + "") === 0 && error_remark !== "") {
          this.$message.warning("异常数量为零，不用填写异常备注！");
          return;
        }
      } else {
        if (!isnumber(stock_num + "" || stock_num === "")) {
          this.$message.warning("入库数量必须为整数！");
          return;
        }
        if (parseInt(stock_num + "") > parseInt(allot_num + "")) {
          this.$message.warning("入库数量不大于调拨总数量！");
          return;
        }
      }
      this.tableForm.product_go[rowIndex].edit = false;
    },
    //编辑某一行
    editRow(rowIndex) {
      let index = this.tableForm.product_go.findIndex((v) => v.edit);
      if (index !== -1) {
        this.$message.warning("请完成其他行的编辑！");
        return;
      } else {
        this.tableForm.product_go[rowIndex].edit = true;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.allot,
.allotDetail {
  .label-title-model {
    line-height: 30px;
    width: 100%;
    color: #909399;
    font-weight: bold;
    font-size: 15px;
    padding-bottom: 12px;
    text-align: center;
  }
  .product_go {
    .el-form-item--mini.el-form-item {
      margin: 0 !important;
      .spscope {
        word-break: break-all !important;
        line-height: 23px !important;
        padding: 0 !important;
        margin: 0 !important;
        list-style: none !important;
        font-style: normal !important;
        text-decoration: none !important;
        border: none !important;
        display: inline-block !important;
        font-weight: 500 !important;
        font-family: "Microsoft Yahei", sans-serif !important;
        -webkit-tap-highlight-color: transparent !important;
        -webkit-font-smoothing: antialiased !important;
        color: #606266 !important;
        font-size: 12px !important;
      }
    }
  }
}
</style>
