<template>
  <div>
    <dialog-edit :visible.sync="dialogVisible" :editModel="editModel" :form="form" :width="width" :formRules="editModel === 'C' ? formRules : formRulesE"
                 :title="title" :autoSave="autoSave" @onSaved="onSaved" :api="api" ref="edit"
                 labelWidth="90px">
      <dym-form ref="dymForm" :componentList="componentList" :formValue="form" @selectChanged="selectChanged">
      </dym-form>
      <!-- 区域专员 -->
      <el-row :gutter="10">
        <el-col :xs="24" :sm="24" :md="24" :lg="24">
          <el-form-item :label="$t('cyjg.businessRegionInfo.commissionerName')" label-width="110px">
            <select-commissioner v-model="form.areaCommissionerIds" :multiple="multiple" name="commissionerName" @selectChanged="commissionerChanged">
            </select-commissioner>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 业务人员 -->
      <el-row :gutter="10">
        <el-col :xs="24" :sm="24" :md="24" :lg="24">
          <el-form-item :label="$t('cyjg.businessRegionInfo.businessName')" label-width="110px">
            <select-markter v-model="form.areaMarketerIds" :multiple="multiple" name="businessName" @selectChanged="markerChanged">
            </select-markter>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 区域对接人 -->
      <el-row :gutter="10">
        <el-col :xs="24" :sm="24" :md="24" :lg="20">
          <el-form-item :label="$t('cyjg.businessRegionInfo.contactsName')" label-width="110px">
            <select-contacts name="contactsName" :queryParas="contactQuery" :reload="reload.contactReload"
                             :multiple="multiple" v-model="form.areaContacts" @selectChanged="contactChanged"></select-contacts>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :md="24" :lg="4">
          <auth-button @click="showCreate" size="medium" type="primary" :label="$t('common.create')" class="contacts-btn"></auth-button>
        </el-col>
      </el-row>
<!--       引用企业管理新增联系人界面-->
<!--      <contact-maintain-edit :visible.sync="showDetail" :editModel="showModel" :form="item" :regMsg="regMsg"></contact-maintain-edit>-->
      <contact-info-edit @createSuccess="createSuccess" :visible.sync="showDetail" :editModel="showModel" :form="itemData" :regMsg="regMsg"></contact-info-edit>
  </dialog-edit>
  </div>
</template>

<script>
import { DialogEdit, dymForm, authButton, SelectCoreEnterprise } from 'newepoch-components'
import BaseEdit from '@/pages/baseEditPage.js'
import SelectContacts from '@/components/element/cyjg/SelectContacts.vue'
import SelectBigArea from '@/components/element/cyjg/SelectBigArea.vue'
import SelectCommissioner from '@/components/element/cyjg/SelectCommissioner.vue'
import contactInfoEdit from '@/pages/enterpriseInfoManage/supplierInfoManage/contactMaintainEdit.vue'

import businessRegionInfoApi from '@/api/cyjg/businessRegionInfoApi.js'
import SelectMarkter from '@/components/element/cyjg/SelectMarkter.vue'
export default {
  extends: new BaseEdit(),
  name: 'littleAreaEdit',
  components: {
    DialogEdit,
    dymForm,
    authButton,
    SelectContacts,
    SelectCoreEnterprise,
    SelectBigArea,
    SelectCommissioner,
    SelectMarkter,
    contactInfoEdit
  },
  props: {},
  data () {
    let $this = this
    return {
      itemData: {},
      enterpriseType: '60',
      width: '550px',
      showDetail: false,
      showModel: '',
      title: '',
      item: {
        tagCode: '60',
        enterpriseId: ''
      },
      autoSave: false,
      multiple: true,
      contactQuery: {
        companyId: ''
      },
      addForm: {
        areaName: '',
        areaParentId: '',
        businessPeople: [],
        commissioner: [],
        contacts: [],
        coreCompanyId: '',
        coreCompanyName: '',
        largeAreaType: '1'
      },
      updateForm: {
        delBusinessPeople: [],
        deleteCommissioner: [],
        deleteContacts: [],
        insertCommissioner: [],
        insertContacts: [],
        istBusinessPeople: [],
        littleAreaId: ''
      },
      businessPeople: [],
      commissioner: [],
      contacts: [],
      reload: {
        contactReload: false
      },
      componentList: [
        // 核心企业
        {
          value: 'coreCompanyId',
          disabled: false,
          componentName: SelectCoreEnterprise,
          name: 'coreEnterprises',
          label: this.$i18n.messages[this.$i18n.locale].cyjg.businessRegionInfo.coreEnterprise,
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseSelect,
          cols: [24, 24, 24, 24],
          reload: true,
          // 暂时屏蔽
          on: {
            clear () {
              $this.form.shortName = ''
              $this.$set($this.componentList[1], 'disabled', false)
            }
          },
          labelWidth: '110px',
          prop: 'coreCompanyId'
        },
        // 核心企业简称
        {
          value: 'shortName',
          disabled: true,
          componentName: 'el-input',
          label: this.$i18n.messages[this.$i18n.locale].cyjg.businessRegionInfo.shortName,
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseInput,
          cols: [24, 24, 24, 24],
          labelWidth: '110px',
          prop: 'shortName'
        },
        // 大区域
        {
          value: 'bigAreaKeyId',
          disabled: false,
          componentName: SelectBigArea,
          name: 'bigAreas',
          label: this.$i18n.messages[this.$i18n.locale].cyjg.businessRegionInfo.lageArea,
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseSelect,
          queryName: ['coreCompanyId', 'areaType'],
          queryValue: ['coreCompanyId', 'largeAreaType'],
          cols: [24, 24, 24, 24],
          labelWidth: '110px',
          prop: 'bigAreaKeyId',
          loadApi: false
        },
        // 小区域
        {
          value: 'areaName',
          disabled: false,
          componentName: 'el-input',
          maxlength: 50,
          label: this.$i18n.messages[this.$i18n.locale].cyjg.businessRegionInfo.littleArea,
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseInput,
          cols: [24, 24, 24, 24],
          labelWidth: '110px',
          prop: 'areaName'
        },
        // 区域编号
        {
          value: 'areaNumber',
          disabled: true,
          componentName: 'el-input',
          label: this.$i18n.messages[this.$i18n.locale].cyjg.businessRegionInfo.areaNumber,
          placeholder: '',
          cols: [24, 24, 24, 24],
          labelWidth: '110px',
          prop: 'areaNumber'
        }
        // 区域专员
        // {
        //   value: 'areaCommissionerIds',
        //   disabled: false,
        //   componentName: SelectCommissioner,
        //   name: 'areaCommissioners',
        //   label: this.$i18n.messages[this.$i18n.locale].cyjg.businessRegionInfo.commissionerName,
        //   placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseSelect,
        //   cols: [24, 24, 24, 24],
        //   multiple: true,
        //   prop: 'areaCommissionerIds'
        // },
        // 业务人员
        // {
        //   value: 'areaMarketerIds',
        //   disabled: false,
        //   componentName: SelectMarkter,
        //   name: 'areaMarketers',
        //   label: this.$i18n.messages[this.$i18n.locale].cyjg.businessRegionInfo.businessName,
        //   placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseSelect,
        //   cols: [24, 24, 24, 24],
        //   multiple: true,
        //   prop: 'areaMarketerIds'
        // }
      ],
      formRules: {
        // 核心企业
        coreCompanyId: [{
          required: true,
          message: this.regMsg.businessRegionInfo.coreEnterprise,
          trigger: 'change'
        }],
        // 小区域
        areaName: [{
          required: true,
          message: this.regMsg.businessRegionInfo.littleArea,
          trigger: 'blur'
        }],
        shortName: [{
          required: true,
          message: '请填写核心企业简称',
          trigger: 'blur'
        }]
      },
      formRulesE: {
        // 小区域
        areaName: [{
          required: true,
          message: this.regMsg.businessRegionInfo.littleArea,
          trigger: 'blur'
        }]
      }
    }
  },
  computed: {
    api () {
      return businessRegionInfoApi.businessRegionInfoManageApi
    }
  },
  methods: {
    // clearMethod () {
    //   this.form.shortName = ''
    //   this.$set(this.componentList[1], 'disabled', false)
    // },
    setShortNameDisabled (value) {
      if (this.UtilJs.isEmpty(value)) {
        this.$set(this.componentList[1], 'disabled', false)
      } else {
        this.$set(this.componentList[1], 'disabled', true)
      }
    },
    createSuccess () {
      this.reload.contactReload = !this.reload.contactReload
    },
    // 区域专员change事件
    commissionerChanged (val, name, data) {
      let $this = this
      $this.commissioner = data
    },
    // 业务专员change事件
    markerChanged (val, name, data) {
      let $this = this
      $this.businessPeople = data
    },
    // 区域对接人change事件
    contactChanged (val, name, data) {
      let $this = this
      $this.contacts = data
    },
    selectChanged (obj) {
      let $this = this
      // 核心企业绑定值
      if (!$this.UtilJs.isEmpty(obj.coreEnterprisesInfo)) {
        $this.$refs['edit'].$refs['editForm'].clearValidate('shortName')
        $this.item.enterpriseId = obj.coreEnterprisesInfo.keyId
        $this.contactQuery.companyId = obj.coreEnterprisesInfo.keyId
        // this.$set(this.reload, 'contactReload', $this.reload.contactReload)
        $this.reload.contactReload = !$this.reload.contactReload
        $this.addForm.coreCompanyId = obj.coreEnterprisesInfo.keyId
        $this.addForm.coreCompanyName = obj.coreEnterprisesInfo.enterpriseName
        if (this.editModel !== 'E') {
          $this.form.shortName = obj.coreEnterprisesInfo.shortName ? obj.coreEnterprisesInfo.shortName : ''
        }
        // 暂时屏蔽
        // $this.setShortNameDisabled($this.form.shortName)
      }
      // 大区域绑定值
      if (!$this.UtilJs.isEmpty(obj.bigAreasInfo)) {
        $this.addForm.areaParentId = obj.bigAreasInfo.keyId
      } else {
        $this.addForm.areaParentId = ''
      }
      // 区域专员绑定值
      // if (obj.areaCommissionersInfo) {
      //   console.log(obj.areaCommissionersInfo)
      //   $this.commissioner = obj.areaCommissionersInfo
      // }
      // 业务人员绑定值
      // if (obj.areaMarketersInfo) {
      //   console.log(obj.areaMarketersInfo)
      //   $this.businessPeople = obj.areaMarketersInfo
      // }
    },
    onSaved (data) {
      // let $this = this
      if (this.editModel === 'C') {
        // 处理数据结构 区域专员
        this.commissioner.forEach(item => {
          this.addForm.commissioner.push({
            areaCommissionerId: item.areaCommissionerId,
            areaCommissionerName: item.areaCommissionerName
          })
        })
        // 业务人员
        this.businessPeople.forEach(item => {
          this.addForm.businessPeople.push({
            areaMarketerId: item.markterId,
            areaMarketerName: item.markterName
          })
        })
        // 区域对接人
        this.contacts.forEach(item => {
          this.addForm.contacts.push({
            areaContactsId: item.areaContactsId,
            areaContactsName: item.areaContactsName
          })
        })
        // 小区域名称
        this.addForm.areaName = data.areaName
        this.addForm.shortName = this.form.shortName
        businessRegionInfoApi.businessRegionInfoManageApi.addLittleArea(this.addForm).then(res => {
          if (res && res.data === true) {
            this.success(this.regMsg.businessRegionInfo.createSmallSuc)
            this.dialogVisible = false
            this.$emit('handleFilter')
          }
        })
      } else {
        // 小区域ID
        this.updateForm.littleAreaId = data.littleAreaId
        // 区域专员
        let nowCommissioner = []
        if (this.form.areaCommissionerIds !== []) {
          this.form.areaCommissionerIds.forEach(item => {
            this.commissioner.forEach(issue => {
              if (item === issue.areaCommissionerId) {
                nowCommissioner.push(issue)
              }
            })
          })
        }
        // 原数据不为空
        if (data.commissioner !== []) {
          // 现数据不为空
          if (nowCommissioner !== []) {
            data.commissioner.forEach(item => {
              let flag = nowCommissioner.some(issue => {
                if (issue.areaCommissionerId === item.areaCommissionerId) {
                  return true
                }
              })
              if (!flag) {
                this.updateForm.deleteCommissioner.push(item)
              }
            })
          }
        } else {
          this.updateForm.insertCommissioner = nowCommissioner
        }
        // 现数据不为空
        if (nowCommissioner !== []) {
          // 原数据不为空
          if (data.commissioner !== []) {
            nowCommissioner.forEach(item => {
              let flag = data.commissioner.some(issue => {
                if (issue.areaCommissionerId === item.areaCommissionerId) {
                  return true
                }
              })
              if (!flag) {
                this.updateForm.insertCommissioner.push(item)
              }
            })
          }
        } else {
          data.commissioner.forEach(item => {
            this.commissioner.forEach(issue => {
              if (item === issue.areaCommissionerId) {
                this.updateForm.deleteCommissioner.push(issue)
              }
            })
          })
        }
        // 业务人员
        let nowBusinessPeople = []
        if (this.form.areaMarketerIds !== []) {
          this.form.areaMarketerIds.forEach(item => {
            this.businessPeople.forEach(issue => {
              if (item === issue.markterId) {
                nowBusinessPeople.push(issue)
              }
            })
          })
        }
        // 原数据不为空
        if (data.businessPeople !== []) {
          // 现数据不为空
          if (nowBusinessPeople !== []) {
            data.businessPeople.forEach(item => {
              let flag = nowBusinessPeople.some(issue => {
                if (issue.markterId === item.areaMarketerId) {
                  return true
                }
              })
              if (!flag) {
                this.updateForm.delBusinessPeople.push(item)
              }
            })
          }
        } else {
          this.updateForm.istBusinessPeople = nowBusinessPeople
        }
        // 现数据不为空
        if (nowBusinessPeople !== []) {
          // 原数据不为空
          if (data.businessPeople !== []) {
            nowBusinessPeople.forEach(item => {
              let flag = data.businessPeople.some(issue => {
                if (issue.areaMarketerId === item.markterId) {
                  return true
                }
              })
              if (!flag) {
                this.updateForm.istBusinessPeople.push(item)
              }
            })
            let newIstBusinessPeople = []
            this.updateForm.istBusinessPeople.forEach(item => {
              newIstBusinessPeople.push({
                areaMarketerId: item.markterId,
                areaMarketerName: item.markterName
              })
            })
            this.updateForm.istBusinessPeople = newIstBusinessPeople
          }
        } else {
          data.businessPeople.forEach(item => {
            this.businessPeople.forEach(issue => {
              if (item === issue.markterId) {
                this.updateForm.delBusinessPeople.push(issue)
              }
            })
          })
          let newDelBusinessPeople = []
          this.updateForm.delBusinessPeople.forEach(item => {
            newDelBusinessPeople.push({
              areaMarketerId: item.markterId,
              areaMarketerName: item.markterName
            })
          })
          this.updateForm.delBusinessPeople = newDelBusinessPeople
        }
        // 对接人
        let nowContacts = []
        if (this.form.areaContacts !== []) {
          this.form.areaContacts.forEach(item => {
            this.contacts.forEach(issue => {
              if (item === issue.areaContactsId) {
                nowContacts.push(issue)
              }
            })
          })
        }
        // 原数据不为空
        if (data.contacts !== []) {
          // 现数据不为空
          if (nowContacts !== []) {
            data.contacts.forEach(item => {
              let flag = nowContacts.some(issue => {
                if (issue.areaContactsId === item.areaContactsId) {
                  return true
                }
              })
              if (!flag) {
                this.updateForm.deleteContacts.push(item)
              }
            })
          }
        } else {
          this.updateForm.insertContacts = nowContacts
        }
        // 现数据不为空
        if (nowContacts !== []) {
          // 原数据不为空
          if (data.contacts !== []) {
            nowContacts.forEach(item => {
              let flag = data.contacts.some(issue => {
                if (issue.areaContactsId === item.areaContactsId) {
                  return true
                }
              })
              if (!flag) {
                this.updateForm.insertContacts.push(item)
              }
            })
          }
        } else {
          data.contacts.forEach(item => {
            this.contacts.forEach(issue => {
              if (item === issue.areaContactsId) {
                this.updateForm.deleteContacts.push(issue)
              }
            })
          })
        }
        this.updateForm.shortName = this.form.shortName
        this.updateForm.areaName = this.form.areaName
        this.updateForm.areaParentId = this.form.bigAreaKeyId
        if (!this.form.bigAreaKeyId || this.form.bigAreaKeyId.length === 0) {
          this.updateForm.areaParentId = '0'
        }
        businessRegionInfoApi.businessRegionInfoManageApi.updateLittleArea(this.updateForm).then(res => {
          if (res && res.data) {
            this.success(this.regMsg.businessRegionInfo.updateSmallSuc)
            // 暂时屏蔽
            // $this.$set($this.componentList[0], 'reload', !$this.componentList[0].reload)
            this.dialogVisible = false
            this.$emit('handleFilter')
          }
        })
      }
    },
    showCreate () {
      if (this.editModel === 'E') {
        this.item.enterpriseId = this.form.coreCompanyId
      }
      if (!this.form.coreCompanyId) {
        this.warning(this.$i18n.messages[this.$i18n.locale].regMsg.businessRegionInfo.PleaseSelectcoreCompanyName)
        return
      }
      this.showModel = 'C'
      this.item.tagCode = '60'
      this.item.loading = false
      this.itemData = JSON.parse(JSON.stringify(this.item))
      this.showDetail = true
    }
  },
  watch: {
    dialogVisible (val) {
      let $this = this
      if (val) {
        this.$set(this.componentList[1], 'disabled', true)
        $this.contactQuery.companyId = $this.form.coreCompanyId
        this.contactReload = !this.contactReload
        this.$set(this.form, 'largeAreaType', '1')
        $this.form.businessPeople.forEach(it => {
          $this.businessPeople.push({
            markterId: it.areaMarketerId,
            markterName: it.areaMarketerName
          })
        })
        $this.commissioner = $this.form.commissioner
        $this.contacts = $this.form.contacts
        if (this.editModel === 'E') {
          this.$set(this.componentList[0], 'disabled', true)
          this.$set(this.componentList[1], 'disabled', true)
          this.$set(this.componentList[2], 'disabled', false)
          this.$set(this.componentList[3], 'disabled', false)
          this.title = this.$i18n.messages[this.$i18n.locale].cyjg.businessRegionInfo.littleAreaMaintain + '(编辑)'
        } else {
          this.$set(this.componentList[0], 'disabled', false)
          this.$set(this.componentList[1], 'disabled', false)
          this.$set(this.componentList[2], 'disabled', false)
          this.$set(this.componentList[3], 'disabled', false)
          this.title = this.$i18n.messages[this.$i18n.locale].cyjg.businessRegionInfo.littleAreaMaintain + '(新增)'
        }
        if (this.form.bigAreaKeyId === '0') this.form.bigAreaKeyId = ''
      } else {
        $this.form.coreCompanyId = ''
        $this.contactQuery.companyId = ''
        $this.businessPeople = []
        $this.commissioner = []
        $this.contacts = []
        $this.addForm = {
          areaName: '',
          areaParentId: '',
          businessPeople: [],
          commissioner: [],
          contacts: [],
          coreCompanyId: '',
          coreCompanyName: ''
        }
        $this.updateForm = {
          delBusinessPeople: [],
          deleteCommissioner: [],
          deleteContacts: [],
          insertCommissioner: [],
          insertContacts: [],
          istBusinessPeople: [],
          littleAreaId: ''
        }
      }
    },
    // 通过核心企业查询区域对接人，大区域重置
    'form.coreCompanyId' (now, old) {
      if (now !== old && !this.UtilJs.isEmpty(old)) {
        this.contactQuery.companyId = this.form.coreCompanyId
        this.contactReload = !this.contactReload
        this.$set(this.form, 'bigAreaKeyId', '')
        this.$set(this.updateForm, 'areaParentId', '')
        this.$set(this.addForm, 'areaParentId', '')
      }
    }
  }
}
</script>

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