<template>
  <div class="salesOrderDetail">
    <el-row>
      <el-col :span="24">
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          status-icon
          :rules="rulesThis"
          label-width="95px"
          class="demo-ruleForm"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="商品名称" prop="goods_class">
                search-sort
                555
                <!-- <good-class
                  :value="ruleForm.goods_class"
                  :disabled="true"
                  :placeholder="'商品分类'"
                /> -->
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品名称" prop="good_code">
                <el-input
                  v-model="ruleForm.good_name"
                  disabled
                  readonly
                  @focus="showGoodsModel = true"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="销售方" prop="supplierName">
                <search-supplier
                  :type="'1'"
                  :size="searchSize"
                  :value="ruleForm.supplierName"
                  :disabled="
                    !(status === '0' && powers.some((item) => item == '005'))
                  "
                  :isDetail="false"
                  @searchChange="supplierChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="企业客户" prop="customer_code">
                <search-customer
                  :value="ruleForm.customer_code"
                  :names="companyName"
                  :disabled="
                    !(status === '0' && powers.some((item) => item == '005'))
                  "
                  :is-detail="true"
                  @searchChange="customer_code_change"
                />
              </el-form-item>
            </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>
        </el-form>
      </el-col>
      <el-col :span="24" style="padding: 0 0 20px 0">
        <el-form :model="stockForm" ref="stockForm" :size="'mini'">
          <el-table
            :data="stockForm.good_stock"
            border
            :size="'mini'"
            style="width: 100%"
            row-key="key"
          >
            <el-table-column
              prop="wsm_supplierNo"
              label="发货公司编号"
              width="142"
            />

            <el-table-column
              show-overflow-tooltip
              prop="wsm_supplier"
              label="发货公司名称"
              min-width="165"
            />
            <el-table-column prop="wsm_code" label="发货仓库编码" width="170" />
            <el-table-column
              show-overflow-tooltip
              prop="wsm_name"
              label="发货仓库名称"
              min-width="100"
            />
            <el-table-column
              prop="usable_stock"
              label="商品可用库存"
              width="120"
            />

            <el-table-column prop="num" label="下单数量" width="150">
              <template slot-scope="scope">
                <el-form-item
                  :prop="'good_stock.' + scope.$index + '.' + 'num'"
                  :rules="{}"
                  :size="'mini'"
                  style="margin-bottom: 0"
                >
                  <el-input
                    v-model="scope.row.num"
                    :disabled="!scope.row.edit"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="original_price" label="销售价" width="110" />

            <el-table-column
              fixed="right"
              width="80"
              label="操作"
              v-if="status === '0' && powers.some((item) => item == '005')"
            >
              <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="checkStockRow(scope.$index)"
                  ></i>
                </el-tooltip>

                <el-tooltip effect="dark" content="删除" placement="top">
                  <i
                    class="el-icon-delete tb-icon"
                    @click="deleteRow(scope.$index, stockForm.good_stock, 0)"
                  ></i>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </el-col>
      <el-col :span="24" style="padding: 0 0 22px 0">
        <el-form :model="addrForm" ref="addrForm" :size="'mini'">
          <el-table
            :data="addrForm.order_addr"
            border
            :size="'mini'"
            style="width: 100%"
            row-key="key"
          >
            <el-table-column
              prop="receipt_quantity"
              label="收货总数"
              min-width="125"
            />

            <el-table-column
              prop="arrive_time"
              label="最晚收货日期"
              min-width="200"
            />
            <el-table-column
              prop="contactor"
              label="收件联系人"
              min-width="110"
            />

            <el-table-column
              prop="mobile"
              label="收货联系电话"
              min-width="130"
            />

            <el-table-column
              prop="addr_code"
              label="收货省市区"
              min-width="230"
            />
            <el-table-column prop="addr" label="详细地址" min-width="170" />

            <el-table-column
              fixed="right"
              width="80"
              v-if="status === '0' && powers.some((item) => item == '005')"
            >
              <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: #63cbe7"
                    @click="openHouseModal(-1)"
                  ></i>
                </el-tooltip>
              </template>
              <template slot-scope="scope">
                <el-tooltip effect="dark" content="编辑" placement="top">
                  <i
                    class="el-icon-edit tb-icon"
                    @click="openHouseModal(scope.$index)"
                  ></i>
                </el-tooltip>

                <el-tooltip effect="dark" content="删除" placement="top">
                  <i
                    class="el-icon-delete tb-icon"
                    @click="deleteRow(scope.$index, addrForm.order_addr, 1)"
                  ></i>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </el-col>
      <el-col :span="24">
        <in-addr-model
          :show-model="addrmodel"
          @cancel="addrmodel = false"
          @refresh="addrRefresh"
        />

        <addr-add-edit-modal
          :showModel="showAddrAddEditModal"
          :index="AddrAddEditModalIndex"
          :sitem="AddrAddEditModalSitem"
          @cancel="showAddrAddEditModal = false"
          @refresh="showAddrAddEditModalRefresh"
        />
      </el-col>
      <el-col
        :span="24"
        style="text-align: right;padding:0 0 20px 0;"
        v-if="status === '0' && powers.some((item) => item == '005')"
      >
        <el-button :size="'mini'" type="primary" @click="submitForm"
          >保 存
        </el-button>
      </el-col>
    </el-row>
  </div>
</template>
   <script>
import mixinPage from "@/mixins/elPaginationHandle";
import resToken from "@/mixins/resToken";
import asyncRequest from "@/apis/service/sellOut/salesOrder/detail";
import searchStockGoodModal from "@/components/search-stock-good-modal";
import { isnumber, isMobile } from "@/utils/validate";
import inAddrModel from "@/components/in-addr-model";
import AddrAddEditModal from "@/components/addr-add-edit-modal";
export default {
  name: "salesOrderDetail",
  mixins: [mixinPage, resToken],
  props: ["newTime", "id", "sitem"],
  components: { searchStockGoodModal, inAddrModel, AddrAddEditModal },
  watch: {
    newTime: function (val) {
      if (val) {
        this.initForm();
      }
    },
  },
  computed: {
    powers() {
      let tran =
        this.$store.getters.btnList.find(
          (item) => item.menu_route == "salesOrderDetail"
        ) || {};
      if (tran && tran.action && tran.action.length > 0) {
        return tran.action;
      } else {
        return [];
      }
    },
  },

  data() {
    const validatemobile = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("手机号不能为空！"));
      } else {
        if (!isMobile(value)) {
          callback(new Error("手机号格式不正确！"));
        } else {
          callback();
        }
      }
    };
    const validateWeight = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("收货总数不能为空!"));
      } else {
        if (!isnumber(value)) {
          callback(new Error("收货总数仅支持整数!"));
        } else {
          callback();
        }
      }
    };
    return {
      showAddrAddEditModal: false,
      AddrAddEditModalIndex: -1,
      AddrAddEditModalSitem: {},
      showGoodsModel: false,
      stock_code: "",
      companyName: "",
      ruleForm: {
        supplierNo: "", //销售方编码
        supplierName: "", //
        goods_class: [],
        good_name: "",
        good_code: "", // 商品选择
        customer_code: [], // 企业客户选择
      },
      rulesThis: this.rules,
      rules: {
        goods_class: [
          {
            type: "array",
            required: true,
            message: "请选择商品分类",
            trigger: "change",
          },
        ],
        good_code: [
          {
            required: true,
            message: "请选择商品",
            trigger: "blur",
          },
        ],
        customer_code: [
          {
            type: "array",
            required: true,
            message: "请选择企业客户",
            trigger: "change",
          },
        ],
        supplierName: [
          {
            type: "array",
            required: true,
            message: "请选择企业客户",
            trigger: "change",
          },
        ],
      },
      addrForm: {
        order_addr: [], //收货地址
      },
      delAddrList: [],
      delStockList: [],
      addrRules: {
        arrive_time: {
          required: true,
          message: "最晚收货日期不能为空",
          trigger: "change",
        },
        receipt_quantity: {
          required: true,
          validator: validateWeight,
          trigger: "blur",
        },

        contactor: {
          required: true,
          trigger: "blur",
          message: "联系人不能为空",
        },
        mobile: {
          required: true,
          validator: validatemobile,
          trigger: "blur",
        },

        order_addr: {
          type: "array",
          required: true,
          message: "收货省市区不能为空",
          trigger: "change",
        },
        addr: {
          required: true,
          message: "详细地址不能为空",
          trigger: "blur",
        },
      },
      stockForm: {
        good_stock: [], //出货仓库
      },
      loading: false,
      queryId: "",
      status: "",
    };
  },
  mounted() {
    this.initForm();
  },
  methods: {
    async initForm() {
      this.status = "";
      this.queryId = this.$route.query.id;
      this.rulesThis = this.rules;
      this.resetForm();
    },
    showAddrAddEditModalRefresh(e) {
      const { index, item } = e;

      if (index === -1) {
        this.addrForm.order_addr.push(JSON.parse(JSON.stringify(item)));
      } else {
        const {
          arrive_time,
          receipt_quantity,
          contactor,
          mobile,
          addr_code,
          addr_code_name,
          addr,
          id,
        } = JSON.parse(JSON.stringify(item));
        this.addrForm.order_addr[index].receipt_quantity = receipt_quantity;
        this.addrForm.order_addr[index].arrive_time = arrive_time;
        this.addrForm.order_addr[index].contactor = contactor;
        this.addrForm.order_addr[index].mobile = mobile;
        this.addrForm.order_addr[index].addr_code = addr_code;
        this.addrForm.order_addr[index].addr_code_name = addr_code_name;
        this.addrForm.order_addr[index].addr = addr;
        this.addrForm.order_addr[index].id = id;
      }
      this.$refs.addrForm.validateField("addrlist");
    },
    async getstock(code) {
      this.loading = true;
      let model = {
        wsm_code: "",
        page: 1,
        size: 100,
        type_code: code,
        good_code: "",
        good_name: "",
        supplierNo: "",
        stock_low: "",
        stock_up: "",
        warn_low: "",
        warn_up: "",
        stock_max: "1",
      };
      const res = await asyncRequest.getGoodStock(model);
      if (res && res.code === 0 && res.data) {
        this.stockForm = {
          good_stock: [], //出货仓库
        };
        const { list } = res.data;
        list.forEach((v) => {
          let model = {
            num: v.usable_stock,
            usable_stock: v.usable_stock,
            wsm_name: v.wsm_name,
            wsm_supplier: v.wsm_supplier,
            wsm_supplierNo: v.wsm_supplierNo,
            wsm_code: v.wsm_code,
            original_price: v.original_price,
            id: "",
            is_del: 0,
            edit: false,
          };
          this.stockForm.good_stock.push(model);
        });
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(res.message);
      }
      this.loading = false;
    },

    getNewTime() {
      this.newTime = new Date().valueOf();
    },
    async resetForm() {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          const {
            can,
            good_code,
            good_name,
            customer_code,
            companyName,
            status,
            supplierName,
            supplierNo,
          } = this.sitem;
          this.companyName = companyName;
          this.status = status;
          // this.cat_id = can.length > can ? e[e.length - 1] : "";
          let goods_class = [];
          can.forEach((v) => {
            goods_class.push(v.id);
          });
          this.ruleForm = {
            supplierNo: supplierNo ? [supplierNo] : [], //销售方编码
            supplierName: [supplierName] || "", //
            goods_class: goods_class || [],
            good_code: good_code || "", // 商品选择
            good_name: good_name || "",
            customer_code: customer_code ? [customer_code] : "", // 企业客户选择
          };
        }
        if (this.$refs.stockForm) {
          this.$refs.stockForm.resetFields();
          this.$refs.stockForm.clearValidate();
          const { info } = this.sitem;
          this.stockForm = {
            good_stock: [], //出货仓库
          };
          this.delStockList = [];
          if (info && info.length > 0) {
            info.forEach((v) => {
              let model = {
                id: v.id,
                num: v.num || "",
                usable_stock: v.usable_stock || "",
                wsm_name: v.wsm_name || "",
                wsm_supplier: v.wsm_supplier || "",
                wsm_supplierNo: v.wsm_supplierNo || "",
                wsm_code: v.wsm_code || "",
                original_price: v.sale_price || "",
                edit: false,
                is_del: 0,
              };
              this.delStockList.push(model);
              this.stockForm.good_stock.push(model);
            });
          }
        }
        if (this.$refs.addrForm) {
          this.$refs.addrForm.resetFields();
          this.$refs.addrForm.clearValidate();
          const { addrs } = this.sitem;
          this.addrForm = {
            order_addr: [],
          };
          this.delAddrList = [];

          if (addrs && addrs.length > 0) {
            addrs.forEach((v) => {
              const { area_code, city_code, provice_code } = v.addr_code;
              let model = {
                edit: false,
                arrive_time: v.arrive_time || "",
                receipt_quantity: v.receipt_quantity || "",
                contactor: v.contactor || "",
                mobile: v.mobile || "",
                addr_code:
                  area_code && city_code && provice_code
                    ? [provice_code, city_code, area_code]
                    : [],
                addr: v.addr || "",
                id: v.id,
                is_del: 0,
              };
              this.delAddrList.push(model);
              this.addrForm.order_addr.push(model);
            });
          }
        }
      });
    },
    async addGoodsRes(e) {
      if (e && e.length === 1) {
        this.ruleForm.good_name = e[0].good_name;
        this.ruleForm.good_code = e[0].type_code;
      } else {
        this.ruleForm.good_name = "";
        this.ruleForm.good_code = "";
      }
      this.$refs.ruleForm.validateField("good_code");
      if (this.ruleForm.good_code !== "" && this.queryId === "add") {
        await this.getstock(this.ruleForm.good_code);
      } else {
        // this.stockForm = {
        //   good_stock: [], //出货仓库
        // };
      }
    },
    editRow(index) {
      let findex = this.stockForm.good_stock.findIndex((v) => v.edit === true);
      if (findex !== -1) {
        this.$message.warning("当前已有发货仓库信息在编辑，请保存后再试！");
        return;
      } else {
        this.stockForm.good_stock[index].edit = true;
      }
    },
    checkStockRow(index) {
      let total = parseInt(this.stockForm.good_stock[index].usable_stock),
        num = parseInt(this.stockForm.good_stock[index].num);
      if (total === 0) {
        this.$message.warning("该仓库已无该商品库存！不能销售！");
        return;
      } else {
        if (num > total) {
          this.$message.warning("销售数量不能大于可用库存！");
          return;
        } else {
          this.stockForm.good_stock[index].edit = false;
        }
      }
    },
    customer_code_change(e) {
      if (e && e.code) {
        this.ruleForm.customer_code = [e.code];
      } else {
        this.ruleForm.customer_code = [];
      }
      this.$refs.ruleForm.validateField("customer_code");
    },
    openHouseModal(index) {
      this.AddrAddEditModalIndex = index;

      if (index === -1) {
        this.AddrAddEditModalSitem = {};
      } else {
        this.AddrAddEditModalSitem = JSON.parse(
          JSON.stringify(this.addrForm.order_addr[index])
        );
      }
      this.showAddrAddEditModal = true;
      // let findex = this.addrForm.order_addr.findIndex((v) => v.edit === true);
      // if (findex !== -1) {
      //   this.$message.warning("当前已有地址在编辑，请保存后再试！");
      //   return;
      // } else {
      //   if (index === -1) {
      //     this.addrForm.order_addr.push({
      //       edit: true,
      //       arrive_time: "",
      //       receipt_quantity: "",
      //       contactor: "",
      //       mobile: "",
      //       addr_code: [],
      //       addr: "",
      //       id: "",
      //       is_del: 0,
      //     });
      //   } else {
      //     this.addrForm.order_addr[index].edit = true;
      //   }
      // }
    },
    //省市区选择
    select_area_change(e, index) {
      this.addrForm.order_addr[index].addr_code = e;
    },
    //省市区保存某一行
    checkRow(rowIndex) {
      this.$refs.addrForm.validate((valid) => {
        if (valid) {
          this.addrForm.order_addr[rowIndex].edit = false;
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 删除收货地址操作
    deleteRow(index, rows, type) {
      const id = rows[index].id;
      if (type === 0) {
        if (id) {
          this.delStockList.push(rows[index]);
        }
      } else {
        if (id) {
          this.delAddrList.push(rows[index]);
        }
      }
      rows.splice(index, 1);
    },
    async submitForm() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          const { good_code, customer_code, supplierNo } = JSON.parse(
            JSON.stringify(this.ruleForm)
          );
          const { good_stock } = JSON.parse(JSON.stringify(this.stockForm));
          const { order_addr } = JSON.parse(JSON.stringify(this.addrForm));
          if (good_stock.length === 0) {
            this.$message.warning("请填写仓库信息！");
            this.loading = false;
            return;
          }
          if (order_addr.length === 0) {
            this.$message.warning("请填写仓库信息！");
            this.loading = false;
            return;
          }
          let model = {
            supplierNo: supplierNo.join(","),
            id: this.id,
            good_code,
            customer_code: customer_code.join(","), // 账号
            order_addr: [],
            good_stock: [],
          };
          let stockT = 0,
            addrT = 0,
            isStockOk = true,
            isSEdit = false,
            isAEdit = false;
          good_stock.forEach((v1) => {
            if (v1.edit) {
              isSEdit = true;
            }
            if (parseInt(v1.usable_stock) < parseInt(v1.num)) {
              isStockOk = false;
            }
            stockT += parseInt(v1.num);
            let model1 = {
              num: v1.num,
              wsm_code: v1.wsm_code,
              id: v1.id,
              is_del: 0,
            };
            model.good_stock.push(model1);
          });
          order_addr.forEach((v2) => {
            if (v2.edit) {
              isAEdit = true;
            }
            addrT += parseInt(v2.receipt_quantity);
            let model2 = {
              contactor: v2.contactor,
              mobile: v2.mobile,
              arrive_time: v2.arrive_time,
              addr: v2.addr,
              receipt_quantity: v2.receipt_quantity,
              addr_code: v2.addr_code,
              id: v2.id,
              is_del: 0,
            };
            model.order_addr.push(model2);
          });
          if (isSEdit) {
            this.$message.warning("请保存仓库信息！");
            this.loading = false;
            return;
          }
          if (isAEdit) {
            this.$message.warning("请保存地址信息！");
            this.loading = false;
            return;
          }
          if (!isStockOk) {
            this.$message.warning("部分仓库销售数量已大于可用数量！");
            this.loading = false;
            return;
          }
          if (stockT !== addrT) {
            this.$message.warning(
              "库存出库总数量，与收货地址信息中的总数量不一致！"
            );
            this.loading = false;
            return;
          }
          let dAList = JSON.parse(JSON.stringify(this.delAddrList));
          let dSList = JSON.parse(JSON.stringify(this.delStockList));
          good_stock.forEach((v) => {
            let findex = dSList.findIndex((v1) => v1.wsm_code === v.wsm_code);
            if (findex !== -1) {
              dSList.splice(findex, 1);
            }
          });
          order_addr.forEach((v) => {
            let findex = dAList.findIndex(
              (v1) => v1.id !== "" && v1.id === v.id
            );
            if (findex !== -1) {
              dAList.splice(findex, 1);
            }
          });
          dSList.forEach((v) => {
            v.is_del = 1;
          });
          dAList.forEach((v) => {
            v.is_del = 1;
          });

          let res = {};
          if (this.queryId === "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.queryId === "add" ? "添加成功" : "修改成功";
            this.$notify.success({
              title,
              message: "",
            });
            this.showModelThis = false;
            // 刷新
            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>
.salesOrderDetail {
}
</style>
   
   