<template>
  <div>
    <dialog-edit :visible.sync="dialogVisible" :editModel="editModel" :form="splitForm" :width="width" ref="dialog" @onSaved="onSaved"
                 :title="$t('cyjg.businessRegionInfo.areaSplit')" labelWidth="110px" :formRules="formRules" :autoSave="autoSave" :api="api">
      <el-row :gutter="10">
        <el-col :xs="24" :sm="24" :md="24" :lg="23">
          <!-- 核心企业 -->
          <el-form-item :label="$t('cyjg.businessRegionInfo.coreEnterprise')" prop="coreCompanyId">
            <select-core-enterprise v-model="splitForm.coreCompanyId" :clearable="clearable" @selectChanged="coreEnterpriseChanged" class="dymForm">
            </select-core-enterprise>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :xs="24" :sm="24" :md="24" :lg="23">
          <!-- 拆分类型 -->
          <el-form-item :label="$t('cyjg.businessRegionInfo.splitType')" prop="splitType">
            <select-dictionary :store="$store" v-model="splitForm.splitType" :dictTypeCode="dictTypeCode" :clearable="clearable" :name="'splitType'" @selectChanged="dictSelectChanged"></select-dictionary>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :xs="24" :sm="24" :md="24" :lg="23">
          <el-form-item :label="$t('cyjg.businessRegionInfo.splitRegion')" prop="areaId">
            <!-- 被拆分区域(大区域组件) -->
            <select-big-area v-if="splitForm.splitType === '1'" v-model="splitForm.areaId" :queryParas="bigAreaQuery" :loadApi="loadApi"
                             :reload="splitedReload" @selectChanged="queryChanged" class="dymForm"></select-big-area>
            <!-- 被拆分区域(小区域组件) -->
            <select-small-area v-if="splitForm.splitType === '2'" v-model="splitForm.areaId" :queryParas="bigAreaQuery" :loadApi="loadApi"
                               :reload="splitedReload" @selectChanged="queryCompanyChanged" class="dymForm"></select-small-area>
          </el-form-item>
        </el-col>
      </el-row>
      <div v-if="splitForm.splitType === '1'">
        <el-row v-for="(item, index) in splitForm.splitAreaDTOS" :key="item.key">
          <el-col :xs="24" :sm="24" :md="24" :lg="12">
            <el-form-item :label="$t('cyjg.businessRegionInfo.splitedRegion')" :prop="'splitAreaDTOS.' + index + '.splitBigAreaId'" :rules="formRules.splitBigAreaId">
              <!-- 拆分后的区域(大区域组件) -->
              <select-big-area :allowCreate="allowCreate" v-model="item.splitBigAreaId" @selectChanged="selectSplitAreaChanged"
                               :rowIndex="index" :queryParas="bigAreaQuery" :reload="splitedReload" :loadApi="loadApi" class="dymForm">
              </select-big-area>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="11">
            <el-form-item :label="$t('cyjg.businessRegionInfo.attributionRegion')" :prop="'splitAreaDTOS.' + index + '.smallAreaIds'">
              <!-- 归属小区域(小区域组件) -->
              <select-small-area :multiple="multiple" v-model="item.smallAreaIds" @selectChanged="selectAreaIdsChanged"
                                 :rowIndex="index" :queryParas="smallAreaQuery" :reload="areaReload" :loadApi="loadApi" class="dymForm">
              </select-small-area>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="1">
            <!-- 添加 -->
            <el-button circle v-if="index === 1" @click="addBigArea" size="mini" type="primary" icon="el-icon-plus" class="circleBtnMargin"></el-button>
            <!-- 删除 -->
            <el-button circle v-if="index > 1" @click="delBigArea(index)" size="mini" type="primary" icon="el-icon-minus" class="circleBtnMargin"></el-button>
          </el-col>
        </el-row>
      </div>
      <div v-if="splitForm.splitType === '2'">
        <el-row v-for="(item, index) in splitForm.splitAreaDTOS" :key="item.key">
          <el-col :xs="24" :sm="24" :md="24" :lg="11">
            <el-form-item :label="$t('cyjg.businessRegionInfo.splitedRegion')"
                          :prop="'splitAreaDTOS.' + index + '.splitSmallAreaId'"
                          :rules="formRules.splitSmallAreaId">
              <!-- 拆分后的区域(小区域组件) -->
              <select-small-area :allowCreate="allowCreate" v-model="item.splitSmallAreaId"
                                 @selectChanged="selectSplitAreaChanged"
                                 :rowIndex="index" :queryParas="bigAreaQuery"
                                 :reload="splitedReload" :loadApi="loadApi" class="dymForm">
              </select-small-area>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="12">
            <el-form-item :label="$t('cyjg.businessRegionInfo.attributionCompany')" :prop="'splitAreaDTOS.' + index + '.companyIds'">
              <!-- 归属项目公司 -->
              <select-proj-company v-model="item.companyIds" @selectChanged="selectAreaIdsChanged" :multiple="companyMultiple"
                                   :rowIndex="index" :queryParas="companyQuery" :reload="companyReload" class="dymForm">
              </select-proj-company>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="1">
            <el-button circle v-if="index === 1" @click="addSmallArea" size="mini" type="primary" icon="el-icon-plus" class="circleBtnMargin"></el-button>
            <el-button circle v-if="index > 1" @click="delSmallArea(index)" size="mini" type="primary" icon="el-icon-minus" class="circleBtnMargin"></el-button>
          </el-col>
        </el-row>
      </div>
    </dialog-edit>
  </div>
</template>

<script>
// 区域拆分
import SelectBigArea from '@/components/element/cyjg/SelectBigArea.vue'
import SelectSmallArea from '@/components/element/cyjg/SelectSmallArea.vue'
import SelectProjCompany from '@/components/element/cyjg/SelectProjCompany.vue'
import SelectCoreEnterprise from '@/components/element/cyjg/SelectBizCoreEnterprise.vue'
import businessRegionInfoApi from '@/api/cyjg/businessRegionInfoApi.js'
import BaseEdit from '@/pages/baseEditPage.js'
import { dymForm, DialogEdit, SelectDictionary } from 'newepoch-components'
export default {
  extends: new BaseEdit(),
  name: 'regionSplitEdit',
  components: {
    dymForm,
    DialogEdit,
    SelectBigArea,
    SelectSmallArea,
    SelectProjCompany,
    SelectCoreEnterprise,
    SelectDictionary
  },
  data () {
    return {
      loadApi: false,
      autoSave: false,
      allowCreate: true,
      multiple: true,
      companyMultiple: true,
      // 组件重加载(被拆分区域、拆分后区域)
      splitedReload: false,
      // 组件重加载(归属小区域)
      areaReload: false,
      // 组件重加载(归属项目公司)
      companyReload: false,
      clearable: false,
      width: '850px',
      dictTypeCode: 'split_type',
      bigAreaQuery: {
        coreCompanyId: '',
        areaType: ''
      },
      smallAreaQuery: {
        coreCompanyId: '',
        largeAreaId: '',
        areaType: ''
      },
      companyQuery: {
        areaKid: ''
      },
      splitForm: {
        coreCompanyId: '',
        coreCompanyName: '',
        areaId: '',
        splitAreaDTOS: [],
        splitType: '',
        modifyTime: ''
      },
      formRules: {
        coreCompanyId: [{ required: true, message: this.regMsg.businessRegionInfo.coreEnterprise, trigger: 'change' }],
        splitType: [{ required: true, message: this.regMsg.businessRegionInfo.splitType, trigger: 'blur' }],
        areaId: [{ required: true, message: this.regMsg.businessRegionInfo.splitRegion, trigger: 'change' }],
        splitBigAreaId: [
          // { required: true, message: this.regMsg.businessRegionInfo.splitedRegion, trigger: 'change' }
          { trigger: 'change', validator: this.SmallAreaIdLength }
        ],
        smallAreaIds: [{ required: true, message: this.regMsg.businessRegionInfo.smallAreaIds, trigger: 'change' }],
        splitSmallAreaId: [
          // { required: true, message: this.regMsg.businessRegionInfo.splitedRegion, trigger: 'change' },
          { trigger: 'change', validator: this.SmallAreaIdLength }
        ],
        companyIds: [{ required: true, message: this.regMsg.businessRegionInfo.companyIds, trigger: 'change' }]
      }
    }
  },
  computed: {
    api () {
      return businessRegionInfoApi.businessRegionInfoQueryApi
    }
  },
  methods: {
    SmallAreaIdLength (rule, value, callback) {
      if (this.UtilJs.isEmpty(value)) {
        callback(new Error(this.regMsg.businessRegionInfo.splitedRegion))
      } else if (value.length > 50) {
        callback(new Error(this.regMsg.businessRegionInfo.areaLength))
      }
      callback()
    },
    // 核心企业勾选事件
    coreEnterpriseChanged (val, name, data) {
      let $this = this
      // 核心企业-级联-被拆分区域
      if (!$this.UtilJs.isEmpty(data)) {
        $this.bigAreaQuery.coreCompanyId = data.coreCompanyId
        $this.splitForm.coreCompanyName = data.coreCompanyName
        if ($this.splitForm.splitType === '1') {
          $this.bigAreaQuery.areaType = '1'
        } else if ($this.splitForm.splitType === '2') {
          $this.bigAreaQuery.areaType = '2'
        }
        $this.splitedReload = !$this.splitedReload
      }
    },
    // 拆分类型勾选事件
    dictSelectChanged (val, name, data) {
      let $this = this
      if (!$this.UtilJs.isEmpty(data)) {
        if (data.dictId === '1') {
          $this.splitForm.areaId = ''
          $this.bigAreaQuery.areaType = '1'
          $this.$refs['dialog'].resetForm()
          $this.buildBigAreaSplit($this.splitForm)
        } else {
          $this.splitForm.areaId = ''
          $this.bigAreaQuery.areaType = '2'
          $this.$refs['dialog'].resetForm()
          $this.buildSmallAreaSplit($this.splitForm)
        }
      }
    },
    // 被拆分区域change事件(大区域-归属小区域)
    queryChanged (val, name, data) {
      let $this = this
      if (!$this.UtilJs.isEmpty(data)) {
        $this.splitForm.modifyTime = data.modifyTime
        $this.smallAreaQuery.coreCompanyId = $this.splitForm.coreCompanyId
        $this.smallAreaQuery.largeAreaId = data.keyId
        $this.smallAreaQuery.areaType = '2'
        $this.areaReload = !$this.areaReload
      }
    },
    // 被拆分区域change事件(小区域-归属项目公司)
    queryCompanyChanged (val, name, data) {
      let $this = this
      if (!$this.UtilJs.isEmpty(data)) {
        $this.splitForm.modifyTime = data.modifyTime
        $this.companyQuery.areaKid = data.keyId
        $this.companyReload = !$this.companyReload
      }
    },
    // 拆分后区域change事件
    selectSplitAreaChanged (val, name, data, index) {
      let $this = this
      if (data) {
        $this.splitForm.splitAreaDTOS[index].areaId = data.keyId
        $this.splitForm.splitAreaDTOS[index].areaName = data.areaName
      }
      if (name === undefined && data === undefined && index >= 0) {
        $this.splitForm.splitAreaDTOS[index].areaId = ''
        $this.splitForm.splitAreaDTOS[index].areaName = val
      }
    },
    // 归属区域change (1:归属小区域 / 2:归属项目公司)
    selectAreaIdsChanged (val, name, data, index) {
      let $this = this
      if ($this.splitForm.splitType === '1') {
        if (!$this.UtilJs.isNull(index)) {
          $this.splitForm.splitAreaDTOS[index].attributionAreas = []
          if (data.length > 0) {
            for (let i = 0; i < data.length; i++) {
              let p = { areaId: '', areaName: '' }
              p.areaId = data[i].keyId
              p.areaName = data[i].areaName
              $this.splitForm.splitAreaDTOS[index].attributionAreas.push(p)
            }
          }
        }
      } else if ($this.splitForm.splitType === '2') {
        if (!$this.UtilJs.isNull(index)) {
          $this.splitForm.splitAreaDTOS[index].attributionCompanies = []
          if (data.length > 0) {
            for (let i = 0; i < data.length; i++) {
              let p = { companyId: '', companyName: '' }
              p.companyId = data[i].companyId
              p.companyName = data[i].companyName
              $this.splitForm.splitAreaDTOS[index].attributionCompanies.push(p)
            }
          }
        }
      }
    },
    // 初始构造大区域拆分数据
    buildBigAreaSplit (val) {
      val.splitAreaDTOS = []
      for (let i = 0; i < 2; i++) {
        val.splitAreaDTOS.push({
          areaId: '',
          areaName: '',
          smallAreaIds: [],
          attributionAreas: []
        })
      }
    },
    // 初始构造小区域拆分数据
    buildSmallAreaSplit (val) {
      val.splitAreaDTOS = []
      for (let i = 0; i < 2; i++) {
        val.splitAreaDTOS.push({
          areaId: '',
          areaName: '',
          companyIds: [],
          attributionCompanies: []
        })
      }
    },
    // 添加拆分后大区域
    addBigArea () {
      let $this = this
      $this.splitForm.splitAreaDTOS.push({
        areaId: '',
        areaName: '',
        smallAreaIds: [],
        attributionAreas: []
      })
    },
    // 删除添加的拆分后大区域
    delBigArea (index) {
      let $this = this
      $this.splitForm.splitAreaDTOS.splice(index, 1)
    },
    // 添加拆分后小区域
    addSmallArea () {
      let $this = this
      $this.splitForm.splitAreaDTOS.push({
        areaId: '',
        areaName: '',
        companyIds: [],
        attributionCompanies: []
      })
    },
    // 删除添加的拆分后小区域
    delSmallArea (index) {
      let $this = this
      $this.splitForm.splitAreaDTOS.splice(index, 1)
    },
    // 保存
    onSaved () {
      let $this = this
      $this.api.splitArea($this.splitForm).then(res => {
        if (res && res.data) {
          if ($this.splitForm.splitType === '1') {
            $this.success(this.regMsg.businessRegionInfo.splitLargeAreaSuc)
            $this.dialogVisible = false
            $this.$emit('refresh')
          } else if ($this.splitForm.splitType === '2') {
            $this.success(this.regMsg.businessRegionInfo.splitSmallAreaSuc)
            $this.dialogVisible = false
            $this.$emit('refresh')
          }
        }
      })
    }
  },
  watch: {
    visible (val) {
      let $this = this
      if (val) {
        $this.$nextTick(() => {
          $this.$set($this.splitForm, 'splitType', '1')
          $this.buildBigAreaSplit($this.splitForm)
        })
      } else {
        $this.splitForm = {
          coreCompanyId: '',
          coreCompanyName: '',
          areaId: '',
          splitAreaDTOS: [],
          splitType: '',
          modifyTime: ''
        }
        $this.bigAreaQuery = {
          coreCompanyId: '',
          areaType: ''
        }
        $this.smallAreaQuery = {
          largeAreaId: '',
          areaType: ''
        }
        $this.companyQuery = {
          areaKid: ''
        }
      }
    },
    'splitForm.coreCompanyId' (now, old) {
      let $this = this
      let queryFlag = false
      let flag = false
      if ($this.splitForm.splitType === '1') {
        for (let m = 0; m < $this.splitForm.splitAreaDTOS.length; m++) {
          if (!$this.UtilJs.isEmpty($this.splitForm.splitAreaDTOS[m].splitBigAreaId)) {
            queryFlag = true
          }
        }
      } else {
        for (let n = 0; n < $this.splitForm.splitAreaDTOS.length; n++) {
          if (!$this.UtilJs.isEmpty($this.splitForm.splitAreaDTOS[n].splitSmallAreaId)) {
            queryFlag = true
          }
        }
      }
      flag = !$this.UtilJs.isEmpty($this.splitForm.areaId) || queryFlag
      if (now !== old && this.visible && flag) {
        $this.splitForm.areaId = ''
        for (let i = 0; i < $this.splitForm.splitAreaDTOS.length; i++) {
          if ($this.splitForm.splitType === '1') {
            if (!$this.UtilJs.isEmpty($this.splitForm.splitAreaDTOS[i].splitBigAreaId) || $this.splitForm.splitAreaDTOS[i].smallAreaIds.length > 0) {
              $this.splitForm.splitAreaDTOS[i].splitBigAreaId = ''
              $this.splitForm.splitAreaDTOS[i].smallAreaIds = []
            }
          } else {
            if (!$this.UtilJs.isEmpty($this.splitForm.splitAreaDTOS[i].splitSmallAreaId) || $this.splitForm.splitAreaDTOS[i].companyIds.length > 0) {
              $this.splitForm.splitAreaDTOS[i].splitSmallAreaId = ''
              $this.splitForm.splitAreaDTOS[i].companyIds = []
            }
          }
        }
      }
    },
    'splitForm.areaId' (now, old) {
      let $this = this
      if (now !== old && this.visible) {
        for (let i = 0; i < $this.splitForm.splitAreaDTOS.length; i++) {
          if ($this.splitForm.splitType === '1') {
            if ($this.splitForm.splitAreaDTOS[i].smallAreaIds.length > 0) {
              $this.splitForm.splitAreaDTOS[i].smallAreaIds = []
            }
          } else {
            if ($this.splitForm.splitAreaDTOS[i].companyIds.length > 0) {
              $this.splitForm.splitAreaDTOS[i].companyIds = []
            }
          }
        }
      }
    }
  }
}
</script>

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