<template>
  <el-dialog
    v-loading="loading"
    :title="title"
    :center="true"
    align="left"
    top="5vh"
    width="1040px"
    :close-on-click-modal="false"
    :visible.sync="showModelThis"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    @close="closeModel"
  >
    <el-card style="margin-top: -20px">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        status-icon
        :rules="rulesThis"
        size="mini"
        label-width="93px"
        class="demo-ruleForm"
      >
        <el-row :gutter="10">
          <el-col :span="24" style="padding: 0 0 10px 0; margin-top: -5px">
            <el-divider><el-tag size="mini">确认单信息</el-tag></el-divider>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建人" prop="sale_name">
              <el-input
                v-model.trim="ruleForm.sale_name"
                placeholder="请输入创建人"
                :disabled="isDetail"
                maxlength="200"
              /> </el-form-item
          ></el-col>
          <el-col :span="6">
            <el-form-item label="部门" prop="department">
              <el-input
                v-model.trim="ruleForm.department"
                placeholder="请输入部门"
                disabled
                maxlength="200"
              /> </el-form-item
          ></el-col>
          <el-col :span="6">
            <el-form-item label="确认单类型" prop="qrdType">
              <el-input
                v-model.trim="ruleForm.qrdType"
                placeholder="请输入确认单类型"
                disabled
                maxlength="200"
              /> </el-form-item
          ></el-col>
          <el-col :span="6">
            <el-form-item label="采购毛利率" prop="cgd_tax">
              <el-input-number
                style="width: 100%"
                v-model="ruleForm.cgd_tax"
                controls-position="right"
                placeholder="请输入采购毛利率"
                :disabled="isDetail"
                :min="0"
                :precision="2"
                @change="numBlur"
                step-strictly
                :step="0.01"
                :max="100"
              ></el-input-number> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="单据号" prop="sequenceNo">
              <el-input
                v-model.trim="ruleForm.sequenceNo"
                placeholder="请输入单据号"
                :disabled="isDetail"
                maxlength="200"
              />
            </el-form-item> </el-col
          ><el-col :span="12">
            <el-form-item label="PO编号" prop="poNo">
              <el-input
                v-model.trim="ruleForm.poNo"
                placeholder="请输入PO编号"
                :disabled="isDetail"
                maxlength="200"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="购买方公司" prop="khNo">
              <search-select
                :code="ruleForm.khNo"
                :placeholder="'请选择购买方公司'"
                @end="searchChange1"
                :names="searchName1"
                :is-detail="id !== 'add'"
                :type="'1'"
                :size="'mini'"
                :disabled="isDetail"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售方公司" prop="companyNo">
              <search-select
                :code="ruleForm.companyNo"
                :placeholder="'请选择销售方公司'"
                @end="searchChange2"
                :names="searchName2"
                :type="'2'"
                :size="'mini'"
                :is-detail="id !== 'add'"
                :disabled="isDetail"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24" style="padding: 0 0 10px 0; margin-top: -5px">
            <el-divider><el-tag size="mini">收货信息</el-tag></el-divider>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收货人" prop="contactor">
              <el-input
                v-model.trim="ruleForm.contactor"
                placeholder="请输入收货人"
                maxlength="200"
                :disabled="isDetail"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="mobile">
              <el-input
                v-model.trim="ruleForm.mobile"
                placeholder="请输入联系电话"
                maxlength="200"
                :disabled="isDetail"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系地址" prop="addr">
              <el-input
                v-model.trim="ruleForm.addr"
                placeholder="请输入联系地址"
                maxlength="200"
                :disabled="isDetail"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发货时间" prop="sendtime">
              <el-date-picker
                v-model="ruleForm.sendtime"
                :editable="false"
                :clearable="true"
                :size="'mini'"
                :picker-options="pickerOptions"
                placeholder="请选择发货时间"
                style="width: 100%; margin: 0"
                type="datetime"
                :disabled="isDetail"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24" style="padding: 0 0 10px 0; margin-top: -5px">
            <el-divider><el-tag size="mini">商品信息</el-tag></el-divider>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商公司" prop="supplierNo">
              <search-select
                :code="ruleForm.supplierNo"
                :placeholder="'请选择供应商公司'"
                @end="searchChange3"
                :type="'3'"
                :size="'mini'"
                :names="searchName3"
                :disabled="isDetail"
                :is-detail="id !== 'add'"
              /> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="goodName">
              <el-input
                v-model.trim="ruleForm.goodName"
                placeholder="请输入商品名称"
                maxlength="200"
                :disabled="isDetail"
              /> </el-form-item
          ></el-col>

          <el-col :span="6">
            <el-form-item label="数量" prop="goodNum">
              <el-input-number
                style="width: 100%"
                v-model="ruleForm.goodNum"
                controls-position="right"
                placeholder="请输入数量"
                :disabled="isDetail"
                :min="0"
                :precision="0"
                @change="numBlur"
                step-strictly
                :step="1"
                :max="9999999"
              ></el-input-number> </el-form-item
          ></el-col>
          <el-col :span="6">
            <el-form-item label="单价" label-width="55px" prop="goodPice">
              <el-input-number
                v-model="ruleForm.goodPice"
                controls-position="right"
                placeholder="请输入单价"
                style="width: 100%"
                :disabled="isDetail"
                :min="0"
                :precision="2"
                @change="numBlur"
                step-strictly
                :step="0.01"
                :max="9999999"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="货款总额" prop="good_total">
              <el-input
                v-model.number="ruleForm.good_total"
                placeholder="请输入货款总额"
                disabled
                ><template slot="append">元</template></el-input
              >
            </el-form-item></el-col
          >
          <el-col :span="6">
            <el-form-item label="税率" prop="tax">
              <search-select
                :code="ruleForm.tax"
                :placeholder="'请选择税率'"
                @end="searchChange4"
                :type="'4'"
                :size="'mini'"
                :names="searchName4"
                :disabled="isDetail"
                :is-detail="id !== 'add'"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-row>
        <el-col :span="24" style="text-align: right">
          <el-button v-if="!isDetail" type="primary" @click="submitForm"
            >保 存
          </el-button>
          <el-button @click="showModelThis = false">{{
            isDetail ? "关 闭" : "取 消"
          }}</el-button>
        </el-col>
      </el-row>
    </el-card>
  </el-dialog>
</template>
<script>
import asyncRequest from "@/apis/service/network/orderEntry";
import resToken from "@/mixins/resToken";
import { isMobile, isPhone } from "@/utils/validate";
export default {
  name: "Account",
  props: ["showModel", "id", "isDetail"],
  mixins: [resToken],
  data() {
    const validatemobile = (rule, value, callback) => {
      if (value !== "") {
        if (isPhone(value) || isMobile(value)) {
          callback();
        } else {
          callback(new Error("联系电话格式不正确！"));
        }
      } else {
        callback(new Error("请输入联系电话！"));
      }
    };

    return {
      searchName1: "",
      searchName2: "",
      searchName3: "",
      searchName4: "",
      company_img: "",
      bm: "",
      roleList: [],
      loading: false,
      title: "添加确认单信息",
      showModelThis: this.showModel,
      ruleForm: {},
      rulesThis: this.rules,
      pickerOptions: {
        disabledDate: (time) => {
          return time.getTime() > new Date().valueOf();
        },
      },
      //  validator: validateLicense,
      rules: {
        sale_name: [
          {
            required: true,
            message: "请输入创建人",
            trigger: "blur",
          },
        ],
        department: [
          {
            required: true,
            message: "请输入部门",
            trigger: "blur",
          },
        ],
        cgd_tax: [
          {
            required: true,
            message: "请输入采购毛利率",
            trigger: "blur",
          },
        ],
        supplierNo: [
          {
            type: "array",
            required: true,
            message: "请选择供应商公司",
            trigger: "change",
          },
        ],
        qrdType: [
          {
            required: true,
            message: "请输入订单类型",
            trigger: "blur",
          },
        ],
        good_total: [
          {
            required: true,
            message: "请输入货款总金额",
            trigger: "blur",
          },
        ],
        sequenceNo: [
          {
            required: true,
            message: "请输入单据号",
            trigger: "blur",
          },
        ],
        poNo: [
          {
            required: true,
            message: "请输入PO编号",
            trigger: "blur",
          },
        ],
        khNo: [
          {
            type: "array",
            required: true,
            message: "请选择购买方公司",
            trigger: "change",
          },
        ],
        tax: [
          {
            type: "array",
            required: true,
            message: "请选择税率",
            trigger: "change",
          },
        ],
        companyNo: [
          {
            type: "array",
            required: true,
            message: "请选择销售方公司",
            trigger: "change",
          },
        ],
        contactor: [
          {
            required: true,
            message: "请输入收货人",
            trigger: "blur",
          },
        ],
        mobile: [
          {
            required: true,
            validator: validatemobile,
            trigger: "blur",
          },
        ],
        addr: [
          {
            required: true,
            message: "请输入联系地址",
            trigger: "blur",
          },
        ],

        sendtime: [
          {
            required: true,
            message: "请输入发货时间",
            trigger: "change",
          },
        ],

        goodName: [
          {
            required: true,
            message: "请输入商品名称",
            trigger: "blur",
          },
        ],
        goodPice: [
          {
            required: true,
            message: "请输入单价",
            trigger: "blur",
          },
        ],
        goodNum: [
          {
            required: true,
            message: "请输入数量",
            trigger: "blur",
          },
        ],
      },
    };
  },
  watch: {
    showModel: function (val) {
      this.showModelThis = val;
      if (val) {
        this.initForm();
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit("cancel");
      }
    },
  },
  methods: {
    closeModel() {
      console.log("closeModel!!");
    },
    searchChange1(e) {
      this.ruleForm.khNo = JSON.parse(JSON.stringify(e));
      this.$refs.ruleForm.validateField("khNo");
      console.log(this.ruleForm.khNo);
    },
    searchChange2(e) {
      this.ruleForm.companyNo = JSON.parse(JSON.stringify(e));
      this.$refs.ruleForm.validateField("companyNo");
    },
    searchChange3(e) {
      this.ruleForm.supplierNo = JSON.parse(JSON.stringify(e));
      this.$refs.ruleForm.validateField("supplierNo");
    },
    searchChange4(e) {
      this.ruleForm.tax = JSON.parse(JSON.stringify(e));
      this.$refs.ruleForm.validateField("tax");
    },
    async initForm() {
      this.setform();
      this.searchName1 = "";
      this.searchName2 = "";
      this.searchName3 = "";
      this.searchName4 = "";
      this.loading = true;
      if (this.id === "add") {
        this.title = "添加确认单信息";
        this.rulesThis = this.rules;
        await this.resetForm();
      } else {
        if (this.isDetail) {
          this.title = "确认单信息详情";
          this.rulesThis = {};
        } else {
          this.title = "修改确认单信息";
          this.rulesThis = this.rules;
        }
        await this.resetForm();
        await this.initData();
      }
      this.loading = false;
    },
    async initData() {
      //KH202104272612 泰康人寿云南分公司玉溪中支
      //CMP20210608140627719  北京万宇恒通国际科贸有限公司
      //GYS-20210416-0316 北京顺捷玖芊科技有限公司

      const res = await asyncRequest.detail({ id: this.id });
      if (res && res.code === 0) {
        const {
          addr,
          cgd_tax,
          contactor,
          department,
          goodName,
          goodNum,
          goodPice,
          good_total,
          khNo,
          mobile,
          poNo,
          qrdType,
          sale_name,
          sendtime,
          supperinfo,
          supplier,
          supplierNo,
          companyNo,
          sequenceNo,
          knName,
          tax,
          rateid,
        } = res.data;
        this.searchName1 = knName;
        this.searchName2 = supperinfo;
        this.searchName3 = supplier;
        this.searchName4 = tax;
        this.ruleForm = {
          khNo: [khNo],
          companyNo: [companyNo],
          supplierNo: [supplierNo],
          sale_name: sale_name,
          department: department,
          qrdType: qrdType,
          good_total: good_total * 1,
          sequenceNo: sequenceNo, //单据号
          poNo: poNo,
          contactor: contactor,
          mobile: mobile,
          addr: addr,
          sendtime: sendtime,
          goodName: goodName,
          goodPice: goodPice * 1,
          goodNum: goodNum * 1,
          cgd_tax: cgd_tax * 1,
          tax: [rateid],
        };
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(res.message);
      }
    },
    async resetForm() {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          this.setform();
        }
      });
    },
    setform() {
      this.ruleForm = {
        khNo: [],
        companyNo: [],
        supplierNo: [],
        sale_name: "",
        department: "网络部",
        qrdType: "客服确认单",
        good_total: 0,
        sequenceNo: "",
        poNo: "",
        contactor: "",
        mobile: "",
        addr: "",
        sendtime: "",
        goodName: "",
        goodPice: 0,
        goodNum: 0,
        cgd_tax: 0,
        tax: [],
      };
    },
    numBlur() {
      this.ruleForm.good_total = this.setNum(
        this.ruleForm.goodPice * 1 * (this.ruleForm.goodNum * 1)
      );
    },
    setNum(s) {
      return s ? parseFloat(s + "").toFixed(2) : "0";
    },
    async submitForm() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          const obj = JSON.parse(JSON.stringify(this.ruleForm));
          if (parseFloat(obj.goodPice + "").toFixed(2) === "0.00") {
            this.$message.warning("商品单价不能为0！");
            this.loading = false;
            return;
          }
          if (obj.goodNum === 0) {
            this.$message.warning("商品数量不能为0！");
            this.loading = false;
            return;
          }
          obj.companyNo = obj.companyNo[0];
          obj.khNo = obj.khNo[0];
          obj.supplierNo = obj.supplierNo[0];
          obj.tax = obj.tax[0];
          obj.buyer = obj.sale_name;
          obj.buy_depart = obj.department;
          obj.id = this.id;
          for (let key in obj) {
            obj[key] = obj[key] + "";
          }
          let res = {};
          if (this.id === "add") {
            delete obj["id"];
            res = await asyncRequest.add(obj);
          } else {
            res = await asyncRequest.update(obj);
          }
          console.log(res);
          this.loading = false;
          if (res && res.code === 0) {
            const title = this.id === "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>
.finance {
  .activity-upload {
    .btnupload {
      float: left;
      border: 1px solid #cccccc;
      box-sizing: border-box;
      width: 135px;
      height: 135px;
      line-height: 135px;
      text-align: center;
    }
    .Upload {
      width: 135px;
      height: 135px;
      line-height: 135px;
      text-align: center;
      position: absolute;
      line-height: 0px;
      top: 0;
      left: 0;
      line-height: 135px;
    }
    .fileUp {
      vertical-align: top;
    }
    .avatar {
      width: 135px;
      height: 135px;
      line-height: 135px;
      text-align: center;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409eff;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 50px;
      height: 50px;
      line-height: 50px;
      text-align: center;
    }
    .avatar {
      width: 100%;
      height: 100%;
      display: block;
    }
    .txt-tips {
      display: inline-block;
      font-size: 13px;
      color: #606266;
      padding: 18px 0 0 18px;
      p {
        margin: 0;
        line-height: 30px;
      }
    }
    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
  }
}
</style>
