<template>
  <el-dialog :visible.sync="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()" :label-width="$i18n.locale === 'en-US' ? '120px' : '80px'">
        <el-form-item label="父级客户" prop="parentCustomerId">
            <el-select clearable v-model="dataForm.parentCustomerId" placeholder="请选择" @change="changeRootCustomer($event)">
                <el-option v-for="item in rootCustomer" :key="item.customerId" :label="item.customerName" :value="item.customerId">
                </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="子级客户" prop="customerId">
            <el-select clearable v-model="dataForm.customerId" placeholder="请选择" @change="changeSubCustomer($event)">
                <el-option v-for="item in subCustomer" :key="item.customerId" :label="item.customerName" :value="item.customerId">
                </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="是否启用" prop="status">
            <el-select clearable v-model="dataForm.status" placeholder="请选择">
                <el-option v-for="item in statusOptions" :key="item.value" :label="item.name" :value="item.value">
                </el-option>
            </el-select>
        </el-form-item>
      </el-form>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import debounce from 'lodash/debounce'
export default {
  data () {
    return {
      visible: false,
        areaCode: '0',
        rootCustomer: [],
        subCustomer: [],
        statusOptions: [
            { value: 'open', name: '启用' },
            { value: 'closed', name: '禁用' }
        ],
      dataForm: {
        id: '',
        customerId: '',
        parentCustomerId: '',
        pids: '0',
        customerType: '',
        parentCustomerType: '',
        status: '',
        level: '',
        areaCode: '',
        parentAreaCode: ''
      }
    }
  },
  computed: {
    dataRule () {
      return {
        customerId: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        parentCustomerId: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        pids: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        status: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        level: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        areaCode: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        parentAreaCode: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    init () {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.getInfo()
        }
      })
        this.getRootCustomer()
    },
      getRootCustomer () {
          this.$http.get(`/gov/org/agency/areasubagency/0`).then(({ data: res }) => {
              if (res.code !== 0) {
                  return this.$message.error(res.msg)
              }
              this.rootCustomer = res.data
              if (this.rootCustomer.length === 0) {
                  this.$message({
                      type: 'warning',
                      message: '当前客户区划下没有下级客户'
                  })
              }
          }).catch(() => {})
      },
      getSubCustomer () {
        if (this.areaCode) {
            this.$http.get(`/gov/org/agency/areasubagency/` + this.areaCode).then(({ data: res }) => {
                if (res.code !== 0) {
                    return this.$message.error(res.msg)
                }
                res.data.forEach(element => {
                    if (element.customerId !== this.dataForm.parentCustomerId ){
                        this.subCustomer.push(element)
                    }
                });
                if (this.subCustomer.length === 0) {
                    this.$message({
                        type: 'warning',
                        message: '该客户区划下没有下级客户'
                    })
                }
            }).catch(() => {})
        }
      },
      changeRootCustomer (e) {
        this.subCustomer = []
          if (this.dataForm.parentCustomerId) {
              let root = this.rootCustomer.filter(item => item.customerId === this.dataForm.parentCustomerId)[0]
              if (root) {
                  this.dataForm.parentAreaCode = root.areaCode

                  this.areaCode = root.areaCode
                  this.getSubCustomer()
              }
          }
      },
      changeSubCustomer (e) {
          if (this.dataForm.customerId) {
              let root = this.subCustomer.filter(item => item.customerId === this.dataForm.customerId)[0]
              if (root) {
                  this.dataForm.level = root.level
                  this.dataForm.areaCode = root.areaCode
              }
          }
      },
    // 获取信息
    getInfo () {
      this.$http.get(`/oper/crm/customerRelation/${this.dataForm.id}`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }
      }).catch(() => {})
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.$http[!this.dataForm.id ? 'post' : 'put']('/oper/crm/customerRelation/save', this.dataForm).then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        }).catch(() => {})
      })
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>
