<template>
  <ele-modal
    custom-class="ele-dialog-form"
    :visible.sync="visible"
    v-if="visible"
    :title="title"
    width="80%"
    @close="cancel"
  >
    <el-tabs v-model="activeName" type="card">
      <el-tab-pane label="基本信息" name="base">
        <el-form
          label-width="100px"
          ref="form"
          :model="form"
          :rules="rules"
          style="margin-top: 30px"
        >
          <el-row>
            <el-col :span="8">
              <el-form-item label="客户名称" prop="name">
                <el-input placeholder="请输入" v-model="form.name"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户代码" prop="serialNo">
                <el-input
                  placeholder="请输入"
                  v-model="form.serialNo"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户简称" prop="simpleName">
                <el-input
                  placeholder="请输入"
                  v-model="form.simpleName"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="授信额度" prop="authorizationLimit">
                <el-input
                  placeholder="请输入"
                  v-model.number="form.authorizationLimit"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="地址" prop="addressId">
                <el-cascader
                  clearable
                  v-model="form.addressId"
                  :options="options.cityDataLabel"
                  ref="address"
                  style="width: 100%"
                ></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="详细地址" prop="address">
                <el-input
                  placeholder="请输入"
                  v-model="form.address"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="是否存在上级集团公司"
                prop="hasParentGroup"
                label-width="155px"
              >
                <el-radio v-model="form.hasParentGroup" :label="1">是</el-radio>
                <el-radio v-model="form.hasParentGroup" :label="0">否</el-radio>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="经营范围" prop="businessScope">
                <el-input
                  placeholder="请输入"
                  v-model="form.businessScope"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="所属行业" prop="industry">
                <el-cascader
                  :options="options.categoryData"
                  v-model="form.industry"
                  style="width: 100%"
                  ref="industry"
                >
                </el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="主营产品" prop="mainProduct">
                <el-input
                  placeholder="请输入"
                  v-model="form.mainProduct"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="企业类型" prop="companyCategoryId">
                <DictSelection
                  dictName="企业类型"
                  clearable
                  v-model="form.companyCategoryId"
                >
                </DictSelection>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="单位电话" prop="phone">
                <el-input placeholder="请输入" v-model="form.phone"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="登记日期" prop="registerDate">
                <el-date-picker
                  style="width: 100%"
                  clearable
                  v-model="form.registerDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="请选择日期"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="官方行业" prop="officialIndustry">
                <el-input
                  placeholder="请输入"
                  v-model="form.officialIndustry"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="统一社会信用代码	"
                prop="unifiedSocialCreditCode"
                 label-width="130px"
              >
                <el-input
                  placeholder="请输入"
                  v-model="form.unifiedSocialCreditCode"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="businessLicenseFile" label="营业执照附件">
                <fileUpload
                  v-model="form.businessLicenseFiles"
                  module="main"
                  :showLib="false"
                  :limit="1"
                />
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="备注" prop="remark">
                <el-input
                  type="textarea"
                  resize="none"
                  v-model="form.remark"
                  :rows="2"
                  placeholder="请输入"
                  size="small"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="银行信息" name="bank">
        <ele-pro-table
          ref="table"
          :columns="bankColumns"
          :datasource="tableBankData"
          height="350px"
          :need-page="false"
        >
          <!-- 表头工具栏 -->
          <template v-slot:toolbar>
            <el-button type="primary" @click="addBank">添加</el-button>
          </template>
          <template v-slot:action="{ row, $index }">
            <el-link type="primary" @click="handleBankDel(row, $index)"
              >删除</el-link
            >
          </template>
          <template v-slot:accountName="{ row }">
            <el-input v-model="row.accountName" placeholder="请输入"></el-input>
          </template>
          <template v-slot:accountNo="{ row }">
            <el-input v-model="row.accountNo" placeholder="请输入"></el-input>
          </template>
          <template v-slot:bankName="{ row }">
            <el-input v-model="row.bankName" placeholder="请输入"></el-input>
          </template>
          <template v-slot:interbankNo="{ row }">
            <el-input v-model="row.interbankNo" placeholder="请输入"></el-input>
          </template>
        </ele-pro-table>
      </el-tab-pane>
      <el-tab-pane label="联系人信息" name="link">
        <ele-pro-table
          ref="linkTable"
          :columns="linkColumns"
          :datasource="tableLinkData"
          height="350px"
          :need-page="false"
        >
          <!-- 表头工具栏 -->
          <template v-slot:toolbar>
            <el-button type="primary" @click="addLink">添加</el-button>
          </template>
          <template v-slot:action="{ row, $index }">
            <el-link type="primary" @click="handleLinkDel(row, $index)"
              >删除</el-link
            >
          </template>
          <template v-slot:linkName="{ row }">
            <el-input v-model="row.linkName" placeholder="请输入"></el-input>
          </template>
          <template v-slot:mobilePhone="{ row }">
            <el-input v-model="row.mobilePhone" placeholder="请输入"></el-input>
          </template>
          <template v-slot:phone="{ row }">
            <el-input v-model="row.phone" placeholder="请输入"></el-input>
          </template>
          <template v-slot:email="{ row }">
            <el-input v-model="row.email" placeholder="请输入"></el-input>
          </template>
          <template v-slot:post="{ row }">
            <el-input v-model="row.post" placeholder="请输入"></el-input>
          </template>
          <template v-slot:ifChief="{ row }">
            <el-select v-model="row.ifChief" placeholder="请选择" class="w100">
              <el-option
                v-for="item in ifChiefList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </template>
          <template v-slot:status="{ row }">
            <DictSelection
              dictName="客户联系人状态"
              v-model="row.status"
            ></DictSelection>
          </template>
          <template v-slot:remark="{ row }">
            <el-input v-model="row.remark" placeholder="请输入"></el-input>
          </template>
        </ele-pro-table>
      </el-tab-pane>
      <el-tab-pane label="其他信息" name="other">
        <el-form
          label-width="100px"
          ref="otherForm"
          :model="otherForm"
          :rules="otherRules"
          style="margin-top: 30px"
        >
          <el-row>
            <el-col :span="8">
              <el-form-item label="结算方式" prop="settlementMode">
                <DictSelection
                  dictName="结算方式"
                  clearable
                  v-model="otherForm.settlementMode"
                >
                </DictSelection>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="税率" prop="taxRate">
                <el-input v-model.number="otherForm.taxRate">
                  <template slot="append">%</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="折扣率" prop="discount">
                <el-input v-model.number="otherForm.discount">
                  <template slot="append">%</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="分管部门:"
                prop="deptId"
                style="margin-bottom: 22px"
              >
                <deptSelect
                  v-model="otherForm.deptId"
                  @changeGroup="change_principalDep"
                  placeholder="请选择分管部门"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="业务员:" prop="salesmanId">
                <personSelect
                  ref="directorRef"
                  v-model="otherForm.salesmanId"
                  :init="false"
                />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="寄件人" prop="sender">
                <el-input placeholder="请输入" v-model="otherForm.sender"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="寄件人电话" prop="senderPhone">
                <el-input
                  placeholder="请输入"
                  v-model.number="otherForm.senderPhone"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="寄件人地址" prop="addressId">
                <el-cascader
                  clearable
                  v-model="otherForm.addressId"
                  :options="options.cityDataLabel"
                  ref="sendAddress"
                  style="width: 100%"
                ></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="寄件人详细地址" prop="address"
                 label-width="130px">
                <el-input
                  placeholder="请输入"
                  v-model="otherForm.address"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>
    </el-tabs>

    <div slot="footer" class="footer">
      <el-button type="primary" @click="save">保存</el-button>
      <el-button @click="cancel">返回</el-button>
    </div>
  </ele-modal>
</template>

<script>
  import {
    contactSave,
    contactUpdate,
    contactDetail
  } from '@/api/saleManage/contact';
  import {
    categoryData,
    CodeToText,
    TextToCode
  } from 'element-china-category-data';
  import fileUpload from '@/components/upload/fileUpload';
  import { cityDataLabel } from 'ele-admin/packages/utils/regions';
  import {
    uploadFile,
    removeFile
  } from '@/api/system/file/index.js';
  import dictMixins from '@/mixins/dictMixins';
  import deptSelect from '@/components/CommomSelect/dept-select.vue';
  import personSelect from '@/components/CommomSelect/person-select.vue';
  export default {
    props: {
      categoryId: String
    },
    mixins: [dictMixins],
    components: {
      fileUpload,
      deptSelect,
      personSelect
    },
    data() {
      return {
        visible: false,
        title: '',
        row: {},
        activeName: 'base',
        form: {
          address: '',
          addressId: 0,
          addressName: '',
          authorizationLimit: 0,
          businessLicenseFiles: [],
          businessLicenseFile: {},
          businessScope: '',
          categoryId: '',
          companyCategoryId: '',
          companyCategoryName: '',
          hasParentGroup: 0,
          industryCode: '',
          industryFullName: '',
          mainProduct: '',
          name: '',
          officialIndustry: '',
          phone: '',
          registerDate: '',
          remark: '',
          serialNo: '',
          simpleName: '',
          type: 1,
          unifiedSocialCreditCode: ''
        },
        otherForm: {
          settlementMode: '',
          settlementModeName: '',
          taxRate: 0,
          address: '',
          addressId: '',
          deptId: '',
          deptName: '',
          discount: 0,
          salesmanId: '',
          salesmanName: '',
          sender: '',
          senderPhone: ''
        },
        // removeBankList: [],
        // removeLinkList: [],
        tableBankData: [],
        tableLinkData: [],
        ifChiefList: [
          {
            value: 0,
            label: '非首要'
          },
          {
            value: `2`,
            label: '首要'
          }
        ],
        bankColumns: [
          {
            type: 'index',
            width: 55,
            align: 'center'
          },
          {
            label: '单位名称',
            prop: 'accountName',
            slot: 'accountName',
            action: 'accountName'
          },
          {
            label: '银行账号',
            prop: 'accountNo',
            slot: 'accountNo',
            action: 'accountNo'
          },
          {
            label: '开户行',
            prop: 'bankName',
            slot: 'bankName',
            action: 'bankName'
          },
          {
            label: '银行银联号',
            prop: 'interbankNo',
            prop: 'interbankNo',
            slot: 'interbankNo',
            action: 'interbankNo'
          },
          {
            action: 'action',
            slot: 'action',
            label: '操作'
          }
        ],
        linkColumns: [
          {
            type: 'index',
            width: 55,
            align: 'center'
          },
          {
            label: '联系人名称',
            prop: 'linkName',
            slot: 'linkName',
            action: 'linkName'
          },
          {
            label: '手机',
            prop: 'mobilePhone',
            slot: 'mobilePhone',
            action: 'mobilePhone'
          },
          {
            label: '电话',
            prop: 'phone',
            slot: 'phone',
            action: 'phone'
          },
          {
            label: '邮箱',
            prop: 'email',
            prop: 'email',
            slot: 'email',
            action: 'email'
          },
          {
            label: '职务',
            prop: 'post',
            prop: 'post',
            slot: 'post',
            action: 'post'
          },
          {
            label: '状态',
            prop: 'status',
            prop: 'status',
            slot: 'status',
            action: 'status'
          },
          {
            label: '是否首要',
            prop: 'ifChief',
            prop: 'ifChief',
            slot: 'ifChief',
            action: 'ifChief'
          },
          {
            label: '备注',
            prop: 'remark',
            prop: 'remark',
            slot: 'remark',
            action: 'remark'
          },
          {
            action: 'action',
            slot: 'action',
            label: '操作'
          }
        ],
        rules: {
          name: [
            { required: true, message: '请输入客户名称', trigger: 'blur' }
          ],
          authorizationLimit: [
            { required: true, message: '请输入授信额度', trigger: 'change' }
          ]
        },
        otherRules: {
          settlementMode: [
            { required: true, message: '请输入结算方式', trigger: 'blur' }
          ],
          taxRate: [
            { required: true, message: '请输入税率', trigger: 'change' }
          ]
        },
        options: {
          cityDataLabel,
          categoryData
        },
        // 提交状态
        loading: false,
        // 是否是修改
        isUpdate: false
      };
    },
    methods: {
      async open(type, row) {
        this.title = type;
        this.row = row;
        this.visible = true;
        if (type == '新建客户') {
        } else {
          this.isUpdate = true;
        this._getById(row.id);
        }
      },

      // 选择负责人部门
      change_principalDep(id, info) {
        this.otherForm.salesmanId = '';
        // 根据部门获取人员
        const params = { groupId: id };
        this.$nextTick(() => {
          this.$refs.directorRef.getList(params);
        });
      },
      addBank() {
        this.tableBankData.push({
          accountName: '',
          accountNo: '',
          bankName: '',
          interbankNo: ''
        });
      },
      addLink() {
        this.tableLinkData.push({
          linkName: '',
          mobilePhone: '',
          phone: '',
          email: '',
          post: '',
          status: '',
          ifChief: 0,
          remark: ''
        });
      },
      handleBankDel(row, index) {
        this.tableBankData.splice(index, 1);
        if (row?.id) {
        //   this.removeBankList.push(row.id);
        }
      },
      handleLinkDel(row, index) {
        this.linkColumns.splice(index, 1);
        if (row?.id) {
        //   this.removeLinkList.push(row.id);
        }
      },
      async save() {
        const isBaseValid = await this.$refs.form.validate();
        const isOtherValid = await this.$refs.form.validate();
        if (!isBaseValid || !isOtherValid) {
          return false;
        }

        this.loading = true;
        // 基本信息处理
        this.form.categoryId = this.categoryId;
        debugger
        if (this.$refs.address.getCheckedNodes()) {
          let node = this.$refs.address.getCheckedNodes()[0];
          if (node) {
            this.form.addressId = node.path.join();;
            this.form.addressName = node.pathLabels.join();
          }
        }
        if (this.$refs.industry.getCheckedNodes()) {
          let node = this.$refs.industry.getCheckedNodes()[0];
          if (node) {
            this.form.industryCode = node.path.join();;
            this.form.industryFullName = node.pathLabels.join();
          }
        }
        if (this.form.companyCategoryId) {
          this.form.companyCategoryName = this.getDictValue(
            '企业类型',
            this.form.companyCategoryId
          );
        }
        if (
          this.form.businessLicenseFiles &&
          this.form.businessLicenseFiles.length > 0
        ) {
          this.form.businessLicenseFile = this.form.businessLicenseFile[0];
        }
        // 其他信息处理
        if (this.form.settlementMode) {
          this.form.settlementModeName = this.getDictValue(
            '结算方式',
            this.form.settlementMode
          );
        }
        if (this.$refs.sendAddress.getCheckedNodes()) {
          let node = this.$refs.sendAddress.getCheckedNodes()[0];
          if (node) {
            this.otherForm.addressId = node.path.join();;
            this.otherForm.addressName = node.pathLabels.join();
          }
        }

        if (!this.isUpdate) {
          delete this.form.id;
        } else {
        //   this.form.removeBankList = this.removeBankList;
        //   this.form.removeLinkList = this.removeLinkList;
        }
        const data = {
          base: this.form,
          other: this.otherForm,
          bankList: this.tableBankData,
          linkList: this.tableLinkData
        };

        if (this.isUpdate) {
          contactUpdate(data)
            .then((res) => {
              this.loading = false;
              this.$message.success("修改成功");
              this.cancel();
              this.$emit('done');
            })
            .catch((e) => {
              this.loading = false;
            });
        } else {
          contactSave(data)
            .then((res) => {
              this.loading = false;
              this.$message.success("新增成功");
              this.cancel();
              this.$emit('done');
            })
            .catch((e) => {
              this.loading = false;
            });
        }
      },
      cancel() {
        this.visible = false;
      },
      async _getById(id) {
        const data = await contactDetail(id);
        this.form = data.base;
        this.otherForm = data.other;
        this.tableBankData = data.bankList;
        this.tableLinkData = data.linkList;
      },
      // 文件上传
      async handlSuccess(params) {
        let res = await uploadFile({
          multiPartFile: params.file,
          module: this.module
        });
        if (res?.data) {
          this.$emit('input', res.data);
        }
      },
      async clearImg() {
        await removeFile({ fileId: this.value.id });
        this.$emit('input', {});
        this.$refs.uploadRef.clearFiles();
      },
      // 限制上传的数量
      handleExceed(files, fileList) {
        this.$message.warning(`最多允许上传一张图片！`);
      }
    }
  };
</script>
