<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
                1010101010
                <!-- <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 />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="销售方" prop="customer_code">
                <search-supplier
                  :value="ruleForm.supplierNo"
                  :placeholder="'销售方公司'"
                  :disabled="
                    !(status === '0' && powers.some((item) => item == '005'))
                  "
                  :isDetail="true"
                  :type="'1'"
                  :names="supplierName"
                  @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"
                  :placeholder="'购买方公司'"
                  :disabled="true"
                  :is-detail="true"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="商品单价" prop="sale_fee">
                <el-input
                  v-model="ruleForm.sale_fee"
                  placeholder="商品单价"
                  disabled
                  ><template slot="append">元</template></el-input
                >
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="下单数量" prop="good_num">
                <el-input
                  v-model="ruleForm.good_num"
                  :disabled="
                    !(status === '0' && powers.some((item) => item == '005'))
                  "
                  placeholder="下单数量"
                />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="商品类型" prop="goodtype">
                <el-select
                  v-model="ruleForm.goodtype"
                  style="width: 100%"
                  :disabled="
                    !(status === '0' && powers.some((item) => item == '005'))
                  "
                  placeholder="商品类型"
                >
                  <el-option
                    v-for="item in goodtypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="发货类型" prop="sendtype">
                <el-select
                  v-model="ruleForm.sendtype"
                  style="width: 100%"
                  :disabled="
                    !(status === '0' && powers.some((item) => item == '005'))
                  "
                  placeholder="发货类型"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-col>

      <el-col
        :span="24"
        style="padding: 0 0 22px 0"
        v-if="ruleForm.sendtype === '1'"
      >
        <div
          style="height: 40px; margin: -10px 0 0 0"
          class="tr"
          v-if="status === '0' && powers.some((item) => item == '005')"
        >
          <download-addr />
          <el-button
            type="primary"
            size="mini"
            @click="addrmodel = true"
            style="margin: 0 0 0 10px"
            >导入收货地址</el-button
          >
        </div>
        <el-form :model="addrForm" ref="addrForm" :size="'mini'">
          <el-table
            :data="addrForm.order_addr"
            border
            :size="'mini'"
            style="width: 100%"
            max-height="350px"
            row-key="key"
          >
            <el-table-column
              show-overflow-tooltip
              prop="receipt_quantity"
              label="收货总数"
              min-width="125"
            />

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

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

            <el-table-column
              prop="addr_code_name"
              label="收货省市区"
              min-width="230"
              show-overflow-tooltip
            />
            <el-table-column
              prop="addr"
              show-overflow-tooltip
              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/zxOrder/detail";
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: { inAddrModel, AddrAddEditModal },
  watch: {
    newTime: function (val) {
      if (val) {
        this.initForm();
      }
    },
  },
  computed: {
    powers() {
      let tran =
        this.$store.getters.btnList.find(
          (item) => item.menu_route == "zxOrderDetail"
        ) || {};
      if (tran && tran.action && tran.action.length > 0) {
        return tran.action;
      } else {
        return [];
      }
    },
  },

  data() {
 
    const validateWeight = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("收货总数不能为空!"));
      } else {
        if (!isnumber(value)) {
          callback(new Error("收货总数仅支持整数!"));
        } else {
          callback();
        }
      }
    };
    return {
      addrmodel: false,
      showAddrAddEditModal: false,
      AddrAddEditModalIndex: -1,
      AddrAddEditModalSitem: {},
      stock_code: "",
      companyName: "",
      supplierName: "",
      ruleForm: {
        zxNo: "",
        customer_code: [],
        supplierNo: [],
        sendtype: "1",
        good_num: "",
        goodtype: "1",
        goods_class: [],
        goods_name: "",
        sale_fee: "",
        good_code: "", // 商品选择
      },
      options: [
        {
          value: "1",
          label: "直接发货",
        },
        {
          value: "2",
          label: "延迟发货",
        },
      ],
      goodtypeOptions: [
        {
          value: "1",
          label: "普通商品",
        },
        {
          value: "2",
          label: "赠品",
        },
        {
          value: "3",
          label: "样品",
        },
      ],
      rulesThis: this.rules,
      rules: {
        zxNo: [
          {
            required: true,
            message: "咨询单号不能为空！",
            trigger: "blur",
          },
        ],
        customer_code: [
          {
            required: true,
            message: "请选择购买方公司",
            trigger: "change",
          },
        ],
        class_cat: [
          {
            required: true,
            message: "请选择商品分类",
            trigger: "change",
          },
        ],
        supplierNo: [
          {
            type: "array",
            required: true,
            message: "请选择销售方公司",
            trigger: "change",
          },
        ],
        sendtype: [
          {
            required: true,
            message: "请选择发货类型",
            trigger: "change",
          },
        ],

        good_num: [
          {
            required: true,
            validator: validateWeight,
            trigger: "blur",
          },
        ],
        goodtype: [
          {
            required: true,
            message: "请选择商品类型",
            trigger: "change",
          },
        ],
        sale_fee: [
          {
            required: true,
            message: "请输入商品单价",
            trigger: "blur",
          },
        ],
      },
      addrForm: {
        order_addr: [], //收货地址
      },
      delAddrList: [],
      delStockList: [],
      loading: false,
      queryId: "",
      status: "",
    };
  },
  mounted() {
    this.initForm();
  },
  methods: {
    async initForm() {
      this.status = "";

      this.rulesThis = this.rules;
      this.resetForm();
    },

    async supplierChange(e) {
      if (e && e.id) {
        this.ruleForm.supplierNo = [e.code];
      } else {
        this.ruleForm.supplierNo = [];
      }
      this.$refs.ruleForm.validateField("supplierNo");
    },

    getNewTime() {
      this.newTime = new Date().valueOf();
    },
    addrRefresh(e) {
      const { list } = e;
      this.addrForm.order_addr.push(...list);
    },
    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,
            supplierNo,
            good_num,
            good_type,
            send_type,
            sale_price,
            supplierName,
            id,
          } = this.sitem;
          this.queryId = id;
          this.companyName = companyName;
          this.supplierName = supplierName;
          this.status = status;
          let goods_class = [];
          can.forEach((v) => {
            goods_class.push(v.id);
          });
          this.ruleForm = {
            good_num: good_num || "",
            goodtype: good_type || "",
            sendtype: send_type || "",
            sale_fee: sale_price || "",
            goods_class: goods_class || [],
            good_code: good_code || "", // 商品选择
            good_name: good_name || "",
            customer_code: customer_code ? [customer_code] : [], // 企业客户选择
            supplierNo: supplierNo ? [supplierNo] : [],
          };
        }

        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_code_name: v.addr_info,
                addr: v.addr || "",
                id: v.id,
                is_del: 0,
              };
              this.delAddrList.push(model);
              this.addrForm.order_addr.push(model);
            });
          }
        }
      });
    },

    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;
    },
 
   
    // 删除收货地址操作
    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);
    },
    showAddrAddEditModalRefresh(e) {
      const { index, item } = e;
  // console.log(addr_code_name);
         console.log(item);
      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("order_addr");
    },
    async submitForm() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          const { customer_code, sendtype, good_num, goodtype, supplierNo } =
            JSON.parse(JSON.stringify(this.ruleForm));
          const { order_addr } = JSON.parse(JSON.stringify(this.addrForm));
          let model = {
            id: this.queryId,
            goodtype: goodtype || "",
            good_num: good_num || "",
            sendtype: sendtype || "",
            customer_code: customer_code.join(","), // 账号
            supplierNo: supplierNo.join(","), // 账号
            remark: "",
            addrlist: [],
          };
          if (sendtype === "1") {
            if (order_addr.length === 0) {
              this.$message.warning("请填写收货地址信息！");
              this.loading = false;
              return;
            }

            let addrT = 0,
              isAEdit = false;
            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.addrlist.push(model2);
            });

            if (isAEdit) {
              this.$message.warning("请保存地址信息！");
              this.loading = false;
              return;
            }

            if (parseInt(good_num) !== addrT) {
              this.$message.warning(
                "库存出库总数量，与收货地址信息中的总数量不一致！"
              );
              this.loading = false;
              return;
            }
            let dAList = JSON.parse(JSON.stringify(this.delAddrList));
            order_addr.forEach((v) => {
              let findex = dAList.findIndex(
                (v1) => v1.id !== "" && v1.id === v.id
              );
              if (findex !== -1) {
                dAList.splice(findex, 1);
              }
            });
            dAList.forEach((v) => {
              v.is_del = 1;
            });
            model.addrlist.push(...dAList);
          }

          let 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>
   
   