<template>
  <el-dialog
    :title="title"
    :center="true"
    align="left"
    top="5vh"
    width="1040px"
    @close="closeModel"
    :close-on-click-modal="false"
    :visible.sync="showModelThis"
    v-loading="loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    append-to-body
  >
    <el-card style="margin-top: -20px">
      <el-row :gutter="10">
        <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="good_code">
                  <good-class
                    :value="ruleForm.goods_class"
                    @handleChange="goods_class_change"
                    :disabled="
                      !(
                        id === 'add' ||
                        (status === '0' && powers.some((item) => item == '005'))
                      )
                    "
                    :placeholder="'商品分类'"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="商品名称" prop="good_code">
                  <el-input
                    v-model="ruleForm.good_name"
                    readonly
                    @focus="showGoodsModel = true"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="企业客户" prop="customer_code">
                  <search-customer
                    :value="ruleForm.customer_code"
                    @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="145"
              />

              <el-table-column
                show-overflow-tooltip
                prop="wsm_supplier"
                label="发货公司名称"
                min-width="145"
              />
              <el-table-column
                prop="wsm_code"
                label="发货仓库编码"
                width="180"
              />
              <el-table-column
                show-overflow-tooltip
                prop="wsm_name"
                label="发货仓库名称"
                min-width="180"
              />
              <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="操作">
                <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)"
                    ></i>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </el-col>
        <el-col :span="24" style="padding: 0 0 22px 0">
          <div style="height: 30px">
            <a href="./static/收货地址模板.xlsx">
              <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"
                ></i>
              </el-tooltip>
            </a>
            <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="openAddModal(-1)"
              ></i>
            </el-tooltip>
          </div>
          <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"
              >
                <template slot-scope="scope">
                  <el-form-item
                    :prop="
                      'order_addr.' + scope.$index + '.' + 'receipt_quantity'
                    "
                    :rules="addrRules.receipt_quantity"
                    :size="'mini'"
                    :style="{ marginBottom: scope.row.edit ? '13px' : '0' }"
                  >
                    <el-input
                      v-model="scope.row.receipt_quantity"
                      :disabled="!scope.row.edit"
                    />
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column
                prop="arrive_time"
                label="最晚收货日期"
                min-width="200"
              >
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'order_addr.' + scope.$index + '.' + 'arrive_time'"
                    :rules="addrRules.arrive_time"
                    :size="'mini'"
                    :style="{ marginBottom: scope.row.edit ? '13px' : '0' }"
                  >
                    <el-date-picker
                      :disabled="!scope.row.edit"
                      v-model="scope.row.arrive_time"
                      type="datetime"
                      style="width: 100%"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      :picker-options="pickerOptions"
                    >
                    </el-date-picker>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                prop="contactor"
                label="收件联系人"
                min-width="110"
              >
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'order_addr.' + scope.$index + '.' + 'contactor'"
                    :rules="addrRules.contactor"
                    :size="'mini'"
                    :style="{ marginBottom: scope.row.edit ? '13px' : '0' }"
                  >
                    <el-input
                      v-model="scope.row.contactor"
                      :disabled="!scope.row.edit"
                    />
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column
                prop="mobile"
                label="收货联系电话"
                min-width="130"
              >
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'order_addr.' + scope.$index + '.' + 'mobile'"
                    :rules="addrRules.mobile"
                    :size="'mini'"
                    :style="{ marginBottom: scope.row.edit ? '13px' : '0' }"
                  >
                    <el-input
                      v-model="scope.row.mobile"
                      :disabled="!scope.row.edit"
                    />
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column
                prop="addr_code"
                label="收货省市区"
                min-width="230"
              >
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'order_addr.' + scope.$index + '.' + 'addr_code'"
                    :rules="addrRules.addr_code"
                    :size="'mini'"
                    :style="{ marginBottom: scope.row.edit ? '13px' : '0' }"
                  >
                    <select-area
                      :value="scope.row.addr_code"
                      :disabled="!scope.row.edit"
                      :size="'mini'"
                      @selectChange="select_area_change($event, scope.$index)"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="addr" label="详细地址" min-width="170">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'order_addr.' + scope.$index + '.' + 'addr'"
                    :rules="addrRules.addr"
                    :size="'mini'"
                    :style="{ marginBottom: scope.row.edit ? '13px' : '0' }"
                  >
                    <el-input
                      v-model="scope.row.addr"
                      :disabled="!scope.row.edit"
                    />
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column fixed="right" width="80">
                <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="编辑"
                    v-if="!scope.row.edit"
                    placement="top"
                  >
                    <i
                      class="el-icon-edit tb-icon"
                      @click="openHouseModal(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, addrForm.order_addr)"
                    ></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"
          />
        </el-col>
        <el-col :span="24" style="text-align: right">
          <el-button :size="'mini'" type="primary" @click="submitForm"
            >保 存
          </el-button>
        </el-col>
      </el-row>
    </el-card>
  </el-dialog>
</template>
   <script>
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 "./in-addr-model";
export default {
  name: "allot",
  props: ["showModel", "id"],
  mixins: [resToken],
  components: { searchStockGoodModal, inAddrModel },
  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) => {
      console.log(value);
      if (value === "") {
        callback(new Error("收货总数不能为空!"));
      } else {
        if (!isnumber(value)) {
          callback(new Error("收货总数仅支持整数!"));
        } else {
          callback();
        }
      }
    };
    return {
      loading: false,
      addrmodel: false,
      title: "新建销售订单",
      showModelThis: this.showModel,
      showGoodsModel: false,
      stock_code: "",
      cat_id: "",
      ruleForm: {
        goods_class: [],
        good_name: "",
        good_code: "", // 商品选择
        customer_code: [], // 企业客户选择
      },
      rulesThis: this.rules,
      rules: {
        good_code: [
          {
            required: true,
            message: "请选择商品",
            trigger: "blur",
          },
        ],
        customer_code: [
          {
            type: "array",
            required: true,
            message: "请选择企业客户",
            trigger: "change",
          },
        ],
      },
      addrForm: {
        order_addr: [], //收货地址
      },
      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",
          },
        ],

       addr_code: [
          {
            type: "array",
            required: true,
            message: "收货省市区不能为空",
            trigger: "change",
          },
        ],
        addr: [
          {
            required: true,
            message: "详细地址不能为空",
            trigger: "blur",
          },
        ],
      },
      stockForm: {
        good_stock: [], //出货仓库
      },
      loading: false,
      id: "",
    };
  },
  watch: {
    showModel: function (val) {
      this.showModelThis = val;
      if (val) {
        this.rulesThis = this.rules;
        this.resetForm();
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit("cancel");
      }
    },
  },
  methods: {
    closeModel() {
      console.log("closeModel!!");
      this.showModelThis = false;
    },
    openAddModal(index) {
      this.addrmodel = true;
    },
    addrRefresh(e) {
      console.log(e);
    },
    DownloadTemplate() {
      if (!this.loading) {
        this.loading = true;
        const bloc = dataURLtoBlob(fileUrl);
        const blob = new Blob([bloc], {
          type: "application/vnd.ms-excel",
        });
        const downLoadEle = document.createElement("a");
        // 通过返回的二进制数据来创建一个对象URL.
        const href = URL.createObjectURL(blob);
        downLoadEle.href = href;
        // 信息表为自定义文件名
        downLoadEle.download = "信息表";
        document.body.appendChild(downLoadEle);
        downLoadEle.click();
        document.body.removeChild(downLoadEle);
        // 当加载完成后释放对象URL.
        window.URL.revokeObjectURL(href);
        // window.open(fileUrl, "_blank");
        this.loading = false;
      }
    },
    goods_class_change(e) {
      this.ruleForm.goods_class = e;
      this.cat_id = e.length > 0 ? e[e.length - 1] : "";
      this.$refs.ruleForm.validateField("goods_class");
      this.ruleForm.good_code = "";
      this.ruleForm.good_name = "";
      this.$refs.ruleForm.validateField("good_code");
    },
    refresh(e) {
      this.showModelThis = e;
      this.$emit("refresh", true);
    },
    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,
            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();
          this.cat_id = "";
          this.ruleForm = {
            goods_class: [],
            good_code: "", // 商品选择
            customer_code: [], // 企业客户选择
          };
        }
        if (this.$refs.stockForm) {
          this.$refs.stockForm.resetFields();
          this.$refs.stockForm.clearValidate();

          this.stockForm = {
            good_stock: [], //出货仓库
          };
        }
        if (this.$refs.addrForm) {
          this.$refs.addrForm.resetFields();
          this.$refs.addrForm.clearValidate();
          this.addrForm = {
            order_addr: [],
          };
        }
      });
    },
    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.id === "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) {
      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: "",
          });
        } 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) {
      rows.splice(index, 1);
    },
    async submitForm() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          const { good_code, customer_code } = JSON.parse(
            JSON.stringify(this.ruleForm)
          );
          const { good_stock } = JSON.parse(JSON.stringify(this.stockForm));
          const { order_addr } = JSON.parse(JSON.stringify(this.addrForm));
          let model = {
            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,
            };
            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,
            };
            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 res = await asyncRequest.add(model);

          this.loading = false;
          if (res && res.code === 0) {
            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>
// .capitalClaim {
.excelUploadBox {
  position: relative;
  width: 100%;
  height: 120px;
  line-height: 120px;
  box-sizing: border-box;
  &:hover {
    cursor: pointer;
  }
  .el-icon-receiving {
    width: 100%;
    text-align: center;
    height: 50px;
    display: block;
    font-size: 32px;
    line-height: 90px;
    color: #d3d4d6;
  }
  .boxM {
    width: 100%;
    display: block;
    text-align: center;
    line-height: 65px;
    height: 60px;
    color: #909399;
  }
}
.excelUpload {
  top: 0;
  left: 0;
  position: absolute;
  z-index: 2;
  width: 100%;
  height: 120px;
  line-height: 120px;
  box-sizing: border-box;
}
.excelUploadRes {
  width: 100%;
  height: 120px;
  line-height: 120px;
  box-sizing: border-box;
  i {
    width: 55px;
    height: 120px;
    line-height: 120px;
    text-align: center;
    font-size: 20px;
    &.fl {
      padding-left: 16px;
    }
    &.fr {
      padding-right: 16px;
      &:hover {
        cursor: pointer;
      }
    }
  }
  span {
    width: 386px;
    line-height: 16px;
    margin: 52px 0 0 0;
    font-size: 16px;
  }
}
// }
</style>