<template>
  <el-row class="addForm">
    <el-col :span="24">
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rulesThis"
        ref="ruleForm"
        :size="'mini'"
        label-width="85px"
        class="demo-ruleForm"
      >
        <el-row>
          <el-col :span="12">
            <div class="label-title-model">出库仓库信息：</div>
            <el-form-item label="业务公司" prop="out_companyNo">
              <search-work-company
                :value="ruleForm.out_companyNo"
                :size="'mini'"
                :disabled="
                  !(id === 'add' || (status === '0' && powers.some((i) => i == '005')))
                "
                :is-detail="id !== 'add'"
                :placeholder="'业务公司'"
                @searchChange="supplierChange($event, 'out_companyNo')"
              />
            </el-form-item>
            <el-form-item label="公司" prop="supplier_code">
              <search-supplier
                :value="ruleForm.supplier_code"
                :placeholder="'请选择公司'"
                :size="'mini'"
                :is-detail="id !== 'add'"
                :disabled="
                  !(id === 'add' || (status === '0' && powers.some((i) => i == '005')))
                "
                :names="supplier_name"
                @searchChange="selectSupplierOut"
              />
            </el-form-item>
            <el-form-item label="仓库" prop="stock_code">
              <search-stock
                :value="ruleForm.stock_code"
                :isDetail="id !== 'add'"
                :disabled="
                  !(id === 'add' || (status === '0' && powers.some((i) => i == '005')))
                "
                :size="'mini'"
                :placeholder="'请选择仓库'"
                :isRelation="true"
                :companyCode="supplier_code"
                :names="''"
                @searchChange="selectStockOut"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <div class="label-title-model">入库仓库信息：</div>
            <el-form-item label="业务公司" prop="in_companyNo">
              <search-work-company
                :value="ruleForm.in_companyNo"
                :names="''"
                :size="'mini'"
                :disabled="
                  !(id === 'add' || (status === '0' && powers.some((i) => i == '005')))
                "
                :is-detail="id !== 'add'"
                :placeholder="'业务公司'"
                @searchChange="supplierChange($event, 'in_companyNo')"
              />
            </el-form-item>
            <el-form-item label="公司" prop="supplier_in_code">
              <search-supplier
                :value="ruleForm.supplier_in_code"
                :placeholder="'请选择公司'"
                :size="'mini'"
                :is-detail="id !== 'add'"
                :disabled="
                  !(id === 'add' || (status === '0' && powers.some((i) => i == '005')))
                "
                :names="supplier_in_name"
                @searchChange="selectSupplierIn"
              />
            </el-form-item>
            <el-form-item label="仓库" prop="stock_in_code">
              <search-stock
                :value="ruleForm.stock_in_code"
                :isDetail="id !== 'add'"
                :size="'mini'"
                :disabled="
                  !(id === 'add' || (status === '0' && powers.some((i) => i == '005')))
                "
                :placeholder="'请选择仓库'"
                :isRelation="true"
                :companyCode="supplier_in_code"
                :names="''"
                @searchChange="selectStockIn"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-col>
    <el-col
      :span="24"
      v-if="
        !(
          (status == '3' && powers.some((i) => i == '022')) ||
          (status == '4' && powers.some((i) => i == '023'))
        )
      "
    >
      <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"
            label="操作"
            width="80"
            v-if="id === 'add' || (status === '0' && powers.some((i) => i == '005'))"
          >
            <template slot="header" slot-scope="scope">
              <span>操作</span>
              <el-tooltip
                style="margin: 3px 0 0 0"
                effect="dark"
                class="fr"
                content="添加"
                placement="top"
              >
                <i
                  class="el-icon-circle-plus-outline tb-icon"
                  style="color: #6954f0; magin: 0 0 0 10px"
                  @click="openGoodsModel"
                ></i>
              </el-tooltip>
            </template>
            <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-delete tb-icon"
                  @click="deleteRow(scope.$index, tableForm.product_go)"
                ></i>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </el-col>
    <el-col :span="24" style="text-align: right; padding: 10px 0 10px 0">
      <el-button
        type="primary"
        :size="'mini'"
        @click="submitForm"
        v-if="id === 'add' || (status === '0' && powers.some((i) => i == '005'))"
        >保 存
      </el-button>
    </el-col>
    <el-col :span="24">
      <search-stock-good-modal
        :show-model="showGoodsModel"
        :code="stock_code"
        @cancel="showGoodsModel = false"
        @searchChange="addGoodsRes"
      />
    </el-col>
  </el-row>
</template>
<script>
import asyncRequest from "@/apis/service/stock/allot/detail";
import searchStockGoodModal from "@/components/search-stock-allot-good-modal";
import resToken from "@/mixins/resToken";
import { isnumber } from "@/utils/validate";
import config from "./columns"; //表格列参数
export default {
  name: "allot",
  props: ["showModel", "id", "sitem", "newTime"],
  mixins: [resToken],
  components: { searchStockGoodModal },
  computed: {
    powers() {
      const tran =
        this.$store.getters.btnList.find((item) => item.menu_route == "allotDetail") ||
        {};
      const { action } = tran ?? {};
      return action ?? [];
    },
  },
  data() {
    return {
      showGoodsModel: false,
      status: "",
      supplier_code: "",
      supplier_name: "",
      supplier_in_code: "",
      supplier_in_name: "",
      stock_code: "",
      stock_in_code: "",
      loading: false,
      showModelThis: this.showModel,
      delList: [],
      ruleForm: {
        supplier_code: [], //出库供应商code
        stock_code: [], //出库仓库code
        supplier_in_code: [], //入库供应商code
        stock_in_code: [], //入库仓库code
        in_companyNo: "",
        out_companyNo: "",
      },
      tableForm: {
        product_go: [], //出库商品
      },
      rulesThis: this.rules,
      tableFormThis: config.tableFormThis,
      rules: {
        in_companyNo: [
          {
            required: true,
            message: "请选择入库方业务公司",
            trigger: "change",
          },
        ],
        out_companyNo: [
          {
            required: true,
            message: "请选择出库方业务公司",
            trigger: "change",
          },
        ],
        supplier_code: [
          {
            type: "array",
            required: true,
            message: "请选择供应商",
            trigger: "change",
          },
        ],
        stock_code: [
          {
            type: "array",
            required: true,
            message: "请选择仓库",
            trigger: "change",
          },
        ],
        supplier_in_code: [
          {
            type: "array",
            required: true,
            message: "请选择供应商",
            trigger: "change",
          },
        ],
        stock_in_code: [
          {
            type: "array",
            required: true,
            message: "请选择仓库",
            trigger: "change",
          },
        ],
      },
      columns: [],
      tableData: [],
      oldList: [],
    };
  },
  watch: {
    showModel: function (val) {
      this.showModelThis = val;
      if (val) {
        this.initForm();
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit("cancel");
      }
    },
    newTime: function (val) {
      if (val) {
        this.initForm();
      }
    },
  },
  mounted() {
    this.initForm();
  },
  methods: {
    closeModel() {
      this.$emit("closeModel");
    },

    //业务公司选择
    async supplierChange(e, key) {
      const { code } = e;
      this.ruleForm[key] = code || ""; //业务公司编码
      this.$refs.ruleForm.validateField(key);
    },

    openGoodsModel() {
      if (this.ruleForm.stock_code.length === 0) {
        this.$message.warning("请选择出库仓库！");
        return;
      }

      let index = this.tableForm.product_go.findIndex((v) => v.edit);
      if (index !== -1) {
        this.$message.warning("当前已有商品正在编辑！");
        return;
      }

      this.showGoodsModel = true;
    },

    async initForm() {
      this.loading = true;
      if (this.id === "add") {
        this.status = "";
      }
      this.columns = [];
      this.rulesThis = this.rules;
      await this.resetForm();
      this.loading = false;
    },
    async resetForm() {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          const {
            wsm_in,
            wsm_out,
            wsm_in_name,
            wsm_out_name,
            status,
            out_code,
            in_code,
            in_companyNo,
            out_companyNo,
          } = this.sitem;
          this.status = status || "";
          this.supplier_code = out_code || "";
          this.supplier_name = wsm_out_name || "";
          this.supplier_in_code = in_code || "";
          this.supplier_in_name = wsm_in_name || "";
          this.stock_code = wsm_out || "";
          this.stock_in_code = wsm_in || "";
          this.ruleForm = {
            in_companyNo: in_companyNo || "",
            out_companyNo: out_companyNo || "",
            supplier_code: out_code ? [out_code] : [], //出库供应商code
            stock_code: wsm_out ? [wsm_out] : [], //出库仓库code
            supplier_in_code: in_code ? [in_code] : [], //入库供应商code
            stock_in_code: wsm_in ? [wsm_in] : [], //入库仓库code
          };
        }
        if (this.$refs.tableForm) {
          this.$refs.tableForm.resetFields();
          this.$refs.tableForm.clearValidate();
          const { item, status } = this.sitem;
          this.status = status || "";
          this.tableForm.product_go = [];
          this.delList = [];
          let list = JSON.parse(JSON.stringify(item || []));
          list.forEach((v) => {
            v.usable_num = 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;
            v.spuCode = v.good_type_code;
            this.tableForm.product_go.push(v);
          });
          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";
              }
            }
            if (this.status == "0" || this.status == "") {
              if (v1.prop === "allot_num") {
                v1.width = "150px";
                v1.type = "input";
              }
            }
            this.columns.push(v1);
          });
          this.oldList = list.length === 0 ? [] : JSON.parse(JSON.stringify(list));
        }
      });
    },

    async submitForm() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (this.loading) {
            return;
          }
          this.loading = true;
          if (this.stock_code == this.stock_in_code) {
            this.$message.warning("出入库仓库不能相同！");
            this.loading = false;
            return;
          }
          if (this.tableForm.product_go.length === 0) {
            this.$message.warning("请选择调拨商品！");
            this.loading = false;
            return;
          }
          let index = -1,
            isok = true,
            ishas = true,
            good = [];
          this.tableForm.product_go.forEach((v, i) => {
            if (v.edit && index === -1) {
              index = i;
            }
            let stock = parseInt(v.usable_num),
              num = parseInt(v.allot_num);
            if (stock === 0) {
              ishas = false;
            }
            if (num > stock) {
              isok = false;
            }
          });

          if (index !== -1) {
            this.$message.warning("当前已有商品正在编辑！");
            this.loading = false;
            return;
          }
          if (!ishas) {
            this.$message.warning("部分商品已无可用库存数，无法进行调拨操作！");
            this.loading = false;
            return;
          }
          if (!isok) {
            this.$message.warning("部分商品调拨数量已大于可用库存数！");
            this.loading = false;
            return;
          }

          good = this.getGoodList();
          const { stock_code, stock_in_code } = JSON.parse(JSON.stringify(this.ruleForm));
          console.log(good);
          const model = {
            id: this.id,
            wsm_out: stock_code.toString(), //出库仓库
            wsm_in: stock_in_code.toString(), //入库仓库
            good: good,
          };
          // this.loading = false;
          // return;
          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("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;
        }
      });
    },
    //提交表单前 商品信息list 汇总
    getGoodList() {
      let newList = JSON.parse(JSON.stringify(this.tableForm.product_go)),
        resList = [];
      // console.log(this.oldList);
      // console.log(this.tableForm.product_go);
      if (this.oldList.length === 0) {
        resList = JSON.parse(JSON.stringify(newList));
        resList.map((v1) => {
          console.log(v1);
          v1.id = v1.id || "";
          v1.is_del = "0";
          return v1;
        });
      } else {
        newList.forEach((v1) => {
          let index = this.oldList.findIndex((v2) => v1.bnCode === v2.bnCode);
          console.log(index);
          if (index === -1) {
            let model1 = {
              bnCode: v1.bnCode || "",
              spuCode: v1.spuCode || "",
              id: v1.id || "",
              allot_num: v1.allot_num || "0",
              balance_num: v1.balance_num || "0",
              is_del: "0",
            };
            resList.push(model1);
          } else {
            let model2 = {
              bnCode: v1.bnCode || "",
              spuCode: v1.spuCode || "",
              id: this.oldList[index].id || "",
              allot_num: v1.allot_num || "0",
              balance_num: v1.balance_num || "0",
              is_del: "0",
            };
            resList.push(model2);
          }
        });
      }

      // (dList = JSON.parse(JSON.stringify(this.delList))), console.log(oldList);
      // console.log(oldList);
      // oldList.forEach((v1) => {
      //   let goodModel = {
      //     bnCode: v1.bnCode || "",
      //     spuCode: v1.spuCode || "",
      //     id: v1.id || "",
      //     // good_code: v1.type_code,
      //     allot_num: v1.allot_num || "0",
      //     balance_num: v1.balance_num || "0",
      //     is_del: "0",
      //   };
      //   resList.push(goodModel);
      // });
      // dList.forEach((v2) => {
      //   let goodModel = {
      //     bnCode: v2.bnCode || "",
      //     spuCode: v2.type_code || "",
      //     id: v2.id || "",
      //     allot_num: v2.allot_num,
      //     balance_num: v2.balance_num || "0",
      //     is_del: "1",
      //   };
      //   resList.push(goodModel);
      // });
      return resList;
    },
    // 删除行操作
    deleteRow(index, rows) {
      if (this.id !== "add" && rows[index].id) {
        this.delList.push(rows[index]);
      }
      rows.splice(index, 1);
    },
    //保存某一行
    checkRow(rowIndex) {
      const { usable_num, allot_num } = this.tableForm.product_go[rowIndex];
      console.log(usable_num, allot_num);
      if (!isnumber(allot_num)) {
        this.$message.warning("请输入数字！");
        return;
      }
      if (allot_num === "0") {
        this.$message.warning("调拨数量不能为0！");
        return;
      }
      const num = isNaN(parseInt(usable_num)) ? 0 : parseInt(usable_num);
      if (parseInt(allot_num) > 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;
      }
    },
    // 执行点击商品名称的抛出事件
    addGoodsRes(e) {
      let oldList = JSON.parse(JSON.stringify(this.tableForm.product_go)),
        addList = JSON.parse(JSON.stringify(e)),
        newList = [].concat(...oldList),
        dList = JSON.parse(JSON.stringify(this.delList));
      console.log(addList);
      addList.forEach((v1, index) => {
        let oldindex = oldList.findIndex((v2) => v1.bnCode === v2.bnCode);
        if (oldindex === -1) {
          addList[index].usable_num = addList[index].balance_num;
          addList[index].allot_num = addList[index].balance_num;
          addList[index].edit = false;
          newList.push(addList[index]);
        }
      });
      newList.forEach((v3) => {
        let otherindex = dList.findIndex((v4) => v3.bnCode === v4.bnCode);
        if (otherindex !== -1) {
          dList.splice(otherindex, 1);
        }
      });
      this.tableForm.product_go = [].concat(...newList);
      this.delList = [].concat(...dList);
      this.$refs.tableForm.validateField("product_go");
    },

    // 选择出库供应商
    selectSupplierOut(e) {
      const { code } = e;
      this.ruleForm.supplier_code = code ? [code] : [];
      this.supplier_code = code || "";
      this.ruleForm.stock_code = [];
      this.tableForm.product_go = [];
      this.delList = [];
      this.$refs.ruleForm.validateField("supplier_code");
    },
    // 选择出库仓库
    selectStockOut(e) {
      if (e && e.id) {
        this.ruleForm.stock_code = [e.code];
        this.stock_code = e.code;
      } else {
        this.ruleForm.stock_code = [];
        this.stock_code = "";
      }
      this.tableForm.product_go = [];
      this.delList = [];
      this.$refs.ruleForm.validateField("stock_code");
    },
    // 选择入库仓库
    selectStockIn(e) {
      if (e && e.id) {
        this.ruleForm.stock_in_code = [e.code];
        this.stock_in_code = e.code;
      } else {
        this.ruleForm.stock_in_code = [];
        this.stock_in_code = "";
      }
      this.$refs.ruleForm.validateField("stock_in_code");
    },
    // 选择入库供应商
    selectSupplierIn(e) {
      if (e && e.id) {
        this.ruleForm.supplier_in_code = [e.code];
        this.supplier_in_code = e.code;
      } else {
        this.ruleForm.supplier_in_code = [];
        this.supplier_in_code = "";
      }
      this.ruleForm.stock_in_code = [];
      this.$refs.ruleForm.validateField("supplier_in_code");
    },
  },
};
</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>
