<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" width="40%" :before-close="closePop" >
    <!-- :before-close="handleClose" 如需要可添加进上方 -->
    <div>
      <el-form
        :inline="true"
        :model="supplier"
        class="demo-form-inline"
        label-width="100px"
        :rules="rules"
        ref="supplier"
      >
        <el-row>
          <el-col :span="6">
            <el-form-item label="供应商编码" prop="supplierCode">
              <el-input v-model="supplier.supplierCode"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商名称" prop="supplierName">
              <el-input v-model="supplier.supplierName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="供应商类别" prop="supplierType">
              <!-- <el-input v-model="supplier.type"></el-input> -->
              <!-- <el-autocomplete
                v-model="supplier.supplierType"
                :fetch-suggestions="querySearchAsync"
                @select="handleSelect"
              ></el-autocomplete> -->

              <el-select
                v-model="supplier.supplierType"
                @select="handleSelect"
              >
                <el-option
                  v-for="item in supplierType"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="增值税税率" prop="vatRate">
              <el-input
                v-model="supplier.vatRate"
                @keyup.native="supplier.vatRate = oninput(supplier.vatRate)"
              ></el-input>%
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="纳税人识别号" prop="number">
              <el-input v-model="supplier.number"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="开户银行" prop="bank">
              <el-input v-model="supplier.bank"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="银行账号" prop="bankAccount">
              <el-input v-model="supplier.bankAccount"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-form :model="recordInfo" ref="recordInfo" class="tableclass">
        <el-table
          :row-style="{ color: '#303133' }"
          :header-cell-style="{
            backgroundColor: 'rgb(245, 247, 250)',
            color: '#606266',
          }"
          :data="recordInfo.contacts"
          :class="signAndWeighBoxPatients"
          border
          style="width: 100%"
          max-height="450"
        >
          <!-- 联系人填写 -->
          <el-table-column label="联系人" align="center" width="130">
            <template slot="header" slot-scope="scope">
              <span>联系人<span style="color: red">*</span></span>
            </template>
            <!-- tableRules.name -->
            <template slot-scope="scope">
              <el-form-item
                :prop="'contacts.' + scope.$index + '.name'"
                :rules="
                  scope.row.name != ''
                    ? [
                        {
                          required: 'true',
                          message: '请输入主要联系人',
                          trigger: ['blur'],
                        },
                      ]
                    : null
                "
              >
                <el-input
                  v-model="scope.row.name"
                  style="width: 100px; margin-top: 3px"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <!-- 手机填写 -->
          <el-table-column label="手机" align="center" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.phone"
                style="width: 120px"
              ></el-input>
              <div style="visibility: hidden">/</div>
            </template>
          </el-table-column>
          <!-- id填写======================================================= -->
          <el-table-column label="id" v-if="false">
            <template slot-scope="scope">
              <el-input v-model="scope.row.id" style="width: 100px"></el-input>
              <div style="visibility: hidden">/</div>
            </template>
          </el-table-column>
          <!-- 联系地址填写 -->
          <el-table-column label="联系地址" align="center" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.address"
                style="width: 120px"
              ></el-input>
              <div style="visibility: hidden">/</div>
            </template>
          </el-table-column>
          <!-- 首要联系人填写 -->
          <el-table-column align="center" width="130px">
            <template slot="header" slot-scope="scope">
              <span>首要联系人<span style="color: red">*</span></span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'contacts.' + scope.$index + '.name'">
                <!-- :prop="'contacts.' + scope.$index + '.name'"  如需添加可在上方标签加入 -->
                <el-select
                  v-model="scope.row.is_first"
                  style="width: 110px"
                  @change="changeName($event, scope)"
                >
                  <el-option
                    v-for="(item, index) in tabList"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column
            label="操作"
            align="center"
            width="150px"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-tooltip
                class="item"
                effect="dark"
                content="新增"
                placement="top"
              >
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-circle-plus-outline"
                  @click="handleAdd(scope.$index, scope.row)"
                >
                </el-button>
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                content="删除"
                placement="top"
              >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.$index, scope.row)"
                >
                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>

    <span slot="footer" class="dialog-footer">
      <el-button @click="closePop">取 消</el-button>
      <el-button type="primary" @click="submitForm('supplier', 'recordInfo')"
        >确 定</el-button
      >
    </span>
  </el-dialog>
</template>

<script>
import {
  getSupplierId,
  getsupplytype,
  getsupplyandcontactone,
  delcontactone,
  savesupply,
  updatesupply,
  getexporthistory,
} from "@/api/supply";
import Template from "../../data/template.vue";
export default {
  data() {
    return {
      show_type: 1,
      supplier_ids: "",
      title: "",
      Template,
      supplierType: [],
      signAndWeighBoxPatients: "sign-and-weigh-box-patients",
      list: ["001", "002"],
      // 表单验证规则
      rules: {
        supplierCode: [
          {
            required: true,
            message: "请填写供应商编号",
            trigger: "blur",
          },
        ],
        supplierName: [
          {
            required: true,
            message: "请填写供应商名称",
            trigger: "blur",
          },
        ],
      },
      tabList: [
        {
          value: 1,
          label: "是",
        },
        {
          value: 0,
          label: "否",
        },
      ],
      tableRules: {
        name: [{ required: true, message: "联系人不能为空", trigger: "blur" }],
      },
      recordInfo: {
        contacts: [{}],
      },
      tableData: [
        {
          id: "",
          contacts: "",
          phone: "",
          address: "",
          FirstConcats: "",
          operate: "",
        },
      ],
      dialogVisible: false,
      supplier: {
        supplierName: "",
        supplierCode: "gsy001",
        supplierType: "请选择类别",
        vatRate: 0,
        number: "",
        bank: "",
        bankAccount: "",
      },
      supply_code: [],
      select_supply: [],
      type: "",
      timeout: null,
      id: "",
      name: "",
    };
  },
  created() {},
  methods: {
    show(data, type) {
      if (type == 1) {
        this.initSupplierData();
        this.show_type = 1;
        this.title = "新增供应商";
        this.getsupplytype();
        this.dialogVisible = true;
      } else if (type == 2) {
        this.getsupplytype();
        // console.log(data,'oop')
        this.show_type = 2;
        this.supplier_ids = data.ID;
        this.title = "编辑供应商";
        this.supplier.supplierCode = data.SupplierCode;
        this.supplier.supplierName = data.SupplierName;
        this.supplier.supplierType = data.SupplierType;

        this.supplier.vatRate = data.VatRate;
        this.supplier.number = data.Number;
        this.supplier.bank = data.Bank;
        this.supplier.bankAccount = data.BankAccount;
        this.getcontacts(data.ID);
        this.dialogVisible = true;
      }
    },

    oninput(num) {
      var str = num;
      var len1 = str.substr(0, 1);
      var len2 = str.substr(1, 1);
      //如果第一位是0，第二位不是点，就用数字把点替换掉
      if (str.length > 1 && len1 == 0 && len2 != ".") {
        str = str.substr(1, 1);
      }
      //第一位不能是.
      if (len1 == ".") {
        str = "";
      }
      //限制只能输入一个小数点
      if (str.indexOf(".") != -1) {
        var str_ = str.substr(str.indexOf(".") + 1);
        if (str_.indexOf(".") != -1) {
          str = str.substr(0, str.indexOf(".") + str_.indexOf(".") + 1);
        }
      }
      //正则替换
      str = str.replace(/[^\d^\.]+/g, ""); // 保留数字和小数点
      str = str.replace(/\.\d\d\d\d$/, ""); // 小数点后只能输两位
      return str;
    },

    closePop() {
      this.dialogVisible = false;
      this.supply_code = [];
      this.supplier.supplierCode = "";
      this.supplier.supplierName = "";
      this.supplier.supplierType = "";
      this.supplier.vatRate = "";
      this.supplier.number = "";
      this.supplier.bank = "";
      this.supplier.bankAccount = "";
      this.recordInfo.contacts = [{}];
    },

    // 获取供应商编码接口
    initSupplierData() {
      getSupplierId().then((res) => {
        if (res.data.state == 1) {
          this.supplier.supplierCode =
            res.data.data.supplycode[0].supplier_code;
        }
      });
    },

    getsupplytype() {
      // 获取供应商类别接口
      getsupplytype()
        .then((res) => {
          if (res.status == 200) {
            this.supplierType = res.data.data.list;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },

    handleSelect(item) {
      this.supplier.name = item.value;
      this.supplier.value = item.name;
    },

    //  验证表单内容
    submitForm(supplier, formName) {
      if (this.show_type == 1) {
        this.$refs[supplier].validate((valid) => {
          if (valid) {
            this.$refs[formName].validate((valid) => {
              if (valid) {
                this.recordInfo.contacts.forEach((el) => {
                  if (!el.phone) {
                    el.phone = "";
                  }
                  if (!el.address) {
                    el.address = "";
                  }
                  if (!el.id) {
                    el.id = 0;
                  }
                });
                let params = {
                  suppliercode: this.supplier.supplierCode || "",
                  suppliername: this.supplier.supplierName || "",
                  suppliertype: this.supplier.supplierType || 0,
                  vatrate: this.supplier.vatRate || 0,
                  number: this.supplier.number || "",
                  bank: this.supplier.bank || "",
                  bankaccount: this.supplier.bankAccount || "",
                  contacts: [...this.recordInfo.contacts],
                };
                savesupply(params).then((res) => {
                  if (res.data.state == 1) {
                    this.$message.success("新增成功");
                    this.closePop();
                    this.$emit("init");
                  } else {
                    this.$message.error("新增失败："+res.data.msg);
                    setTimeout(() => {
                      this.closePop();
                    }, 2000);
                  }
                });
              } else {
                return false;
              }
            });
          } else {
            return false;
          }
        });
      } else if (this.show_type == 2) {
        this.$refs[supplier].validate((valid) => {
          if (valid) {
            this.$refs[formName].validate((valid) => {
              if (valid) {
                this.recordInfo.contacts.forEach((el) => {
                  if (!el.phone) {
                    el.phone = "";
                  }
                  if (!el.address) {
                    el.address = "";
                  }
                  if (!el.id) {
                    el.id = 0;
                  }
                });
                let params = {
                  suppliercode: this.supplier.supplierCode || "",
                  suppliername: this.supplier.supplierName || "",
                  id: this.supplier_ids || 0,
                  suppliertype: this.supplier.supplierType || "",
                  vatrate: this.supplier.vatRate || 0,
                  number: this.supplier.number || "",
                  bank: this.supplier.bank || "",
                  bankaccount: this.supplier.bankAccount || "",
                  contacts: [...this.recordInfo.contacts],
                };

                updatesupply(params).then((res) => {
                  if (res.data.state == 1) {
                    this.$message.success("修改成功");
                    this.closePop();
                    this.$emit("init");
                  } else {
                    this.$message.error("修改失败："+res.data.msg);
                    setTimeout(() => {
                      this.closePop();
                    }, 2000);
                  }
                });
              } else {
                return false;
              }
            });
          } else {
            return false;
          }
        });
      }
      this.contactsinfo();
    },

    //  获取供应商与联系人  首次打开新增页面判断是否有首要联系人
    getcontacts(val) {
      let data = {
        value: 1,
        label: "是",
      };
      getsupplyandcontactone({ id: val }).then((res) => {
        if (res.data.code == 0) {
          this.recordInfo.contacts = res.data.data.contact;
          if (this.recordInfo.contacts.length == 0) {
            this.recordInfo.contacts = [{}];
            this.recordInfo.contacts[0].is_first = data.value;
          }
          // else if (this.recordInfo.contacts.length == 1) {
          //     let val = res.data.data.contact[0];
          //     this.recordInfo.contacts[0].is_first = data.value;
          //     this.recordInfo.contacts[0] = {
          //       id: parseFloat(val.id),
          //       name: val.name,
          //       address: val.address,
          //       phone: val.phone,
          //     };
          //   }
        }
      });
    },

    // 首要联系人选择变更动态展示
    changeName(data, scope) {
      let data1 = {
        value: 0,
        label: "否",
      };
      let data2 = {
        value: 1,
        label: "是",
      };
      let arr = [];
      if (this.recordInfo.contacts.length <= 1) {
        this.recordInfo.contacts[0].is_first = data2.value;
      } else {
        this.recordInfo.contacts.forEach((el, index) => {
          if (scope.$index == index) {
            el.is_first = data;
          } else {
            el.is_first = data1.value;
          }
          arr.push(el.is_first);
        });
        if (arr.includes(1)) {
          return;
        } else {
          this.recordInfo.contacts[0].is_first = data2.value;
        }
      }
    },

    // 添加表单行
    handleAdd() {
      let data = {};
      this.recordInfo.contacts.push(data);
    },
    // 删除表单行
    handleDelete(index, data) {
      let params = {
        id: data.id,
      };

      if (this.show_type == 1) {
        if (this.recordInfo.contacts.length <= 1) {
          return;
        } else {
          this.recordInfo.contacts.splice(index, 1);
        }
      } else if (this.show_type == 2) {
        delcontactone(params).then((res) => {
          if (res.data.state == 1) {
            this.$message.success("删除成功");
            this.getcontacts(this.supplier_ids);
          } else {
            this.$message.error(res.data.data.list);
          }
        });
      }
    },

    //表格判断是否填入信息
    contactsinfo() {
      let info = this.tableData;
      return new Promise((resolve, reject) => {
        // if (info) {
        //   resolve(info);
        // } else {
        //   reject("error");
        info.forEach((i) => {
          if (
            i.contacts != "" &&
            i.phone != "" &&
            i.id != "" &&
            i.address != "" &&
            i.FirstConcats != ""
          ) {
            resolve(info);
          } else {
            reject("error");
          }
        });
        // }
      })
        .then((res) => {
          // console.log(res, "ooo");
        })
        .catch((err) => {
          // console.log(err, "ddd");
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.demo-form-inline {
  .el-col-6 {
    width: 50%;
  }
  .el-input {
    width: 75%;
  }
}
.el-dialog__body {
  .el-form-item__content {
    .el-autocomplete {
      width: 75% !important;
    }
    .el-select.el-select--medium {
      width: 85% !important;
    }
  }
}

.tablebtn {
  padding: 10px 12px;
}

/deep/.el-form.tableclass {
  .el-table__header-wrapper {
    .el-table__header {
      width: 625px !important;
    }
  }
  .el-table__body-wrapper.is-scrolling-none {
    .el-table__body {
      width: 625px !important;
    }
  }
}

/deep/ .el-form-item__error {
  // display: none !important;
}
/deep/ .el-table__body-wrapper::-webkit-scrollbar {
  width: 10px;
  height: 10px;
}

/deep/ .el-table__fixed-right{
  bottom: 0 !important;
}
</style>
