<template>
  <div class="busdefendCompany">
    <dialog-edit :title="$t('cyjg.businessRegionInfo.defendCompanyDialogtitle')" :appendToBody="true" :width="width" :api="api" :editModel="editModel"
                 :visible.sync="dialogVisible" :autoSave="autoSave" @onSaved="onSaved" :form="detailForm">
      <el-form :model="detailForm" ref="detailForm" label-width="130px" class="demo-dynamic">
        <div v-for="(item, index) in detailForm.addArr" :key="item.key">
          <el-form-item :prop="'addArr.' + index + '.companyId'" :label="$t('cyjg.financialRegionInfo.CompanyName')"
                        :rules="{ required: true, message: companyNameMessage, trigger: 'change' }">
            <el-col :span="20">
              <select-project-company-name v-model="item.companyId" :reload="companyLoad" :queryParas="queryParas" :rowIndex="index" @selectChanged="coreEnterpriseChanged" class="dymForm"></select-project-company-name>
<!--              <select-finance-company v-model="item.companyId" :reload="companyLoad" :queryParas="queryParas" :rowIndex="index" @selectChanged="coreEnterpriseChanged" class="dymForm"></select-finance-company>-->
            </el-col>
            <el-col :span="4" v-if="index === 0 && editModel === 'C'">  <!-- 第一条数据显示添加按钮 -->
              <!--<span class="addCircle" @click="addDomain">+</span>-->
              <div class="proj-font">
                <i class="iconfont iconzengjia" v-if="index === 0" @click="addDomain()"></i>
              </div>
            </el-col>
            <el-col :span="4" v-if="index > 0 && editModel === 'C'">  <!-- 新增的数据显示删除 -->
              <div class="proj-font">
                <i class="iconfont iconjian" v-if="index > 0" @click.prevent="removeDomain(item)"></i>
              </div>
              <!--<span class="addCircle Companyremove" @click.prevent="removeDomain(item)">-</span>-->
            </el-col>
          </el-form-item>
          <!-- 项目公司对接人 -->
          <el-form-item :prop="'addArr.' + index + '.contactIds'" :label="$t('cyjg.businessRegionInfo.companyGetMan')">
            <el-col :span="17">
              <select-contacts :multiple="multiple" :clearable="clearable" :rowIndex="index" :queryParas="contactParas[index]"
                               v-model="item.contactIds" @selectChanged="contactChanged" class="dymForm" :reload="reload.contactReload"></select-contacts>
            </el-col>
            <el-col :span="3">
              <auth-button @click="contactCreate(index)" type="primary"  size="medium" :label="$t('cyjg.businessRegionInfo.contactCreate')" class="margin-left"></auth-button>
            </el-col>
          </el-form-item>
          <!-- 区域专员 -->
          <el-form-item :prop="'addArr.' + index + '.commissionerIds'" :label="$t('cyjg.businessRegionInfo.commissionerName')">
            <el-col :span="20">
              <SelectCommissioner :multiple="multiple" :clearable="clearable" :rowIndex="index" v-model="item.commissionerIds" @selectChanged="commissionerChanged" class="dymForm"/>
            </el-col>
          </el-form-item>
        </div>
      </el-form>
    </dialog-edit>
    <contact-info-edit :visible.sync="contactDetail" :editModel="contactModel" @createSuccess="saveSuccess" :form="contactItem" :regMsg="regMsg"></contact-info-edit>
    <!--<contact-maintain-edit :visible.sync="contactDetail" :editModel="contactModel" :form="contactItem" :regMsg="regMsg"></contact-maintain-edit>-->
  </div>
</template>

<script>
import { DialogEdit, searchForm, authButton, DataTable, SelectProjectCompanyName } from 'newepoch-components'
import businessRegionInfoApi from '@/api/cyjg/businessRegionInfoApi.js'
import BaseEdit from '@/pages/baseEditPage'
// 项目公司
import SelectFinanceCompany from '@/components/element/cyjg/SelectFinanceCompany.vue'
//  区域专员
import SelectCommissioner from '@/components/element/cyjg/SelectCommissioner.vue'
// 项目公司对接人
import SelectContacts from '@/components/element/cyjg/SelectContacts.vue'
import contactInfoEdit from '@/pages/enterpriseInfoManage/supplierInfoManage/contactMaintainEdit.vue'
// import ContactMaintainEdit from '@/pages/cyjg/businessRegionInfo/contactMaintainEdit.vue'
export default {
  extends: new BaseEdit(),
  name: 'financialRegionInfoList',
  props: {
    visible: {
      required: true,
      type: [Boolean],
      default: function () {
        return false
      }
    },
    form: {
      type: Object,
      default: function () {
        return false
      }
    }
  },
  components: {
    DialogEdit,
    searchForm,
    authButton,
    DataTable,
    SelectCommissioner,
    SelectContacts,
    // ContactMaintainEdit,
    SelectFinanceCompany,
    contactInfoEdit,
    SelectProjectCompanyName
  },
  data () {
    return {
      width: '660px',
      dialogtitle: this.$i18n.messages[this.$i18n.locale].cyjg.businessRegionInfo.defendCompanyDialogtitle,
      companyLoad: false,
      queryParas: {
        coreCompanyId: '',
        companyId: '',
        tag: '150',
        type: '2'
      },
      multiple: true,
      clearable: true,
      reload: {
        contactReload: false
      },
      detectVisible: true,
      contactDetail: false,
      autoSave: false,
      contactModel: 'C',
      companyNameMessage: this.$i18n.messages[this.$i18n.locale].regMsg.businessRegionInfo.companyNameMessage,
      contactItem: {
        tagCode: '150',
        enterpriseId: ''
      },
      //  新增保存数据的数组
      parameterList: {},
      contactParas: [
        {
          companyId: ''
        }
      ],
      detailForm: {
        addArr: [
          {
            contactIds: [],
            commissionerIds: [],
            areaId: '',
            areaName: '',
            companyId: '',
            companyName: '',
            oldCompanyId: '',
            contacts: [],
            commissioners: []
          }
        ]
      }
    }
  },
  methods: {
    saveSuccess () {
      this.reload.contactReload = !this.reload.contactReload
    },
    // 核心企业change事件
    coreEnterpriseChanged (val, name, data, index) {
      let $this = this
      if (!$this.UtilJs.isEmpty(data) && !$this.UtilJs.isNull(index)) {
        $this.contactItem.enterpriseId = data.keyId
        $this.detailForm.addArr[index].companyName = data.enterpriseName
        $this.contactParas[index].companyId = data.keyId
        $this.reload.contactReload = !$this.reload.contactReload
        // 级联清空区域对接人
        $this.detailForm.addArr[index].contactIds = []
      }
    },
    // 项目公司对接人change事件
    contactChanged (val, name, data, index) {
      let $this = this
      if (!$this.UtilJs.isNull(index)) {
        $this.detailForm.addArr[index].contacts = []
        if (data.length > 0) {
          for (let m = 0; m < val.length; m++) {
            for (let n = 0; n < data.length; n++) {
              if (val[m] === data[n].areaContactsId) {
                let p = { enterpriseContactsKeyId: '', enterpriseContactsName: '' }
                p.enterpriseContactsKeyId = data[n].areaContactsId
                p.enterpriseContactsName = data[n].areaContactsName
                $this.detailForm.addArr[index].contacts.push(p)
              }
            }
          }
        }
      }
    },
    // 区域专员change事件
    commissionerChanged (val, name, data, index) {
      let $this = this
      if (!$this.UtilJs.isNull(index)) {
        $this.detailForm.addArr[index].commissioners = []
        if (data.length > 0) {
          for (let j = 0; j < val.length; j++) {
            for (let m = 0; m < data.length; m++) {
              if (val[j] === data[m].areaCommissionerId) {
                let q = { areaCommissionerId: '', areaCommissionerName: '' }
                q.areaCommissionerId = data[m].areaCommissionerId
                q.areaCommissionerName = data[m].areaCommissionerName
                $this.detailForm.addArr[index].commissioners.push(q)
              }
            }
          }
        }
      }
    },
    // 移除添加的表单
    removeDomain (item) {
      let index = this.detailForm.addArr.indexOf(item)
      if (index !== -1) {
        this.detailForm.addArr.splice(index, 1)
      }
    },
    // 增加动态表单
    addDomain () {
      this.detailForm.addArr.push({
        contactIds: [],
        commissionerIds: [],
        areaId: this.form.littleAreaKeyId,
        areaName: this.form.littleAreaName,
        companyId: '',
        companyName: '',
        contacts: [],
        commissioners: []
      })
      this.contactParas.push({
        companyId: ''
      })
    },
    // 打开新增区域对接人界面
    contactCreate (index) {
      if (this.editModel === 'E') {
        this.contactItem.enterpriseId = this.detailForm.addArr[index].companyId
      }
      if (!this.detailForm.addArr[index].companyId) {
        this.warning(this.$i18n.messages[this.$i18n.locale].regMsg.businessRegionInfo.PleaseSelectCompanyName)
        return
      }
      this.contactItem.tagCode = '150'
      this.contactDetail = true
    },
    // 保存方法
    onSaved () {
      let $this = this
      if (this.editModel === 'E') {
        $this.$refs['detailForm'].validate((valid) => {
          if (valid) {
            $this.api.update($this.detailForm.addArr[0].keyId, $this.detailForm.addArr[0]).then(res => {
              if (res.data) {
                $this.success(this.$i18n.messages[this.$i18n.locale].regMsg.businessRegionInfo.update + `${this.dialogtitle}` + this.$i18n.messages[this.$i18n.locale].regMsg.businessRegionInfo.successInfo)
                $this.$emit('saveSuccess')
                $this.dialogVisible = false
              }
            })
          }
        })
      } else {
        let $this = this
        $this.$refs['detailForm'].validate((valid) => {
          if (valid) {
            $this.api.create($this.detailForm.addArr).then(res => {
              if (res.data) {
                $this.success(this.$i18n.messages[this.$i18n.locale].regMsg.businessRegionInfo.innerAdd + `${this.dialogtitle}` + this.$i18n.messages[this.$i18n.locale].regMsg.businessRegionInfo.successInfo)
                $this.$emit('saveSuccess')
                $this.dialogVisible = false
              }
            })
          }
        })
      }
    }
  },
  computed: {
    dialogVisible: {
      get: function () {
        return this.visible
      },
      set: function (value) {
        this.$emit('update:visible', value)
      }
    },
    api () {
      return businessRegionInfoApi.companyView
    }
  },
  watch: {
    visible (val) {
      let $this = this
      if (val) {
        $this.$nextTick(() => {
          $this.$refs['detailForm'].clearValidate()
        })
        $this.queryParas.coreCompanyId = this.form.coreCompanyId
        if (this.editModel === 'E') {
          this.detailForm.addArr[0] = Object.assign(this.detailForm.addArr[0], this.form)
          this.detailForm.addArr[0].commissioners = this.form.commissioner
          this.detailForm.addArr[0].areaId = this.form.areaId
          this.detailForm.addArr[0].areaName = this.form.areaName
          this.detailForm.addArr[0].oldCompanyId = this.form.companyId
          $this.contactParas[0].companyId = this.detailForm.addArr[0].companyId
          $this.reload.contactReload = !$this.reload.contactReload
          $this.queryParas.companyId = $this.detailForm.addArr[0].companyId
        } else if (this.editModel === 'C') {
          this.detailForm.addArr[0].areaId = this.form.littleAreaKeyId
          this.detailForm.addArr[0].areaName = this.form.littleAreaName
          $this.queryParas.companyId = ''
        }
        $this.companyLoad = !$this.companyLoad
      } else {
        this.detailForm.addArr = [
          {
            contactIds: [],
            commissionerIds: [],
            areaId: '',
            areaName: '',
            companyId: '',
            companyName: '',
            oldCompanyId: '',
            contacts: [],
            commissioners: []
          }
        ]
      }
    }
  }
}
</script>

<style scoped lang="scss" src="@/styles/cyjg/businessRegionInfo/defendCompany.scss">
</style>
