<template>
  <el-dialog append-to-body :title="title" :visible.sync="editVisible" @close="handleClose">
    <el-form ref="editForm" :model="editForm" :rules="editRules">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="客户名称" prop="custName">
            <el-input v-model="editForm.custName" placeholder="请输入客户名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="助记名" prop="abbrName">
            <el-input v-model="editForm.abbrName" placeholder="请输入助记名" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="客户类型" prop="custIndustry">
            <el-select v-model="editForm.custIndustry" placeholder="请选择客户类型" style="width: 100%">
              <el-option v-for="item in industryOptions" :key="item.key" :label="item.value" :value="item.key" />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="客户级别" prop="custLevel">
            <el-select v-model="editForm.custLevel" placeholder="请选择客户级别" style="width: 100%">
              <el-option v-for="item in levelOptions" :key="item.value" :label="item.value" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item label="客户来源" prop="source">
            <el-select v-model="editForm.source" placeholder="请选择客户来源" style="width: 100%">
              <el-option v-for="item in sourceOptions" :key="item.value" :label="item.value" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所在地区" required>
            <el-row :gutter="4" style="width: 100%; padding-top: 32px">
              <el-col :span="8">
                <el-select
                  v-model="editForm.province"
                  :disabled="areaEditDisable"
                  placeholder="省"
                  value-key="id"
                  @change="provinceChange">
                  <el-option v-for="item in provinceOptions" :key="item.id" :label="item.distName" :value="item" />
                </el-select>
              </el-col>
              <el-col :span="8">
                <el-select
                  v-model="editForm.city"
                  :disabled="areaEditDisable"
                  placeholder="市"
                  value-key="id"
                  @change="cityChange">
                  <el-option
                    v-for="item in editForm.province ? editForm.province.children : []"
                    :key="item.id"
                    :label="item.distName"
                    :value="item" />
                </el-select>
              </el-col>
              <el-col :span="8">
                <el-select
                  v-model="editForm.region"
                  :disabled="areaEditDisable"
                  placeholder="区"
                  value-key="id"
                  @change="$forceUpdate()">
                  <el-option
                    v-for="item in editForm.city ? editForm.city.children : []"
                    :key="item.id"
                    :label="item.distName"
                    :value="item" />
                </el-select>
              </el-col>
            </el-row>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="详细地址" prop="custAddress">
            <el-input v-model="editForm.custAddress" placeholder="请输入详细地址" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="下次联系时间" prop="followUpDate">
            <el-date-picker
              v-model="editForm.followUpDate"
              format="yyyy-MM-dd HH:mm"
              placeholder="选择下次联系时间"
              style="width: 100%"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="开票抬头" prop="invoiceHeader">
            <el-input v-model="editForm.invoiceHeader" placeholder="请输入详细地址" />
          </el-form-item>
        </el-col> -->
      </el-row>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="editForm.remark"
          maxlength="500"
          placeholder="请输入备注"
          resize="none"
          :rows="5"
          show-word-limit
          type="textarea" />
      </el-form-item>
    </el-form>
    <span slot="footer">
      <el-button v-show="!editForm.id" type="primary" @click="customerSave">保存</el-button>
      <el-button v-show="editForm.id" type="primary" @click="customerEdit">保存</el-button>
      <el-button v-if="!editForm.id" @click="createContact">保存并新建联系人</el-button>
      <el-button @click="editVisible = false">取消</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import to from 'await-to-js'
  import api from '@/api/customer'

  export default {
    data() {
      var checkCustName = async (rule, value, callback) => {
        if (!value) return callback('请输入客户名称')
        let params = {
          custName: value,
          id: this.editForm.id,
        }
        const [err, res] = await to(api.checkCustName(params))
        if (err) return callback('网络错误')
        if (res.data.list) {
          callback('客户名称重复')
        } else {
          callback()
        }
      }
      return {
        title: '新增客户信息',
        // 新增编辑客户弹窗
        editVisible: false,
        areaEditDisable: false,
        editForm: {
          custName: '', // 客户名称
          abbrName: '', // 助记名
          custLocation: '', // 所在地区
          custAddress: '', // 详细地址
          invoiceHeader: '', // 开票抬头
          custStatus: '', // 客户状态(10正常20)
          followUpDate: '', // 最后跟进时间
          custIndustry: '', // 客户类型  (没数据)
          custLevel: '', // 客户级别  (没数据)
          source: '', //客户来源
          province: {}, //省
          city: {}, //市
          region: {}, //区
        },
        editRules: {
          custName: [{ required: true, validator: checkCustName, trigger: 'blur' }],
          custIndustry: [{ required: true, trigger: 'change', message: '请选择客户类型' }],
          // custLevel: [{ required: true, trigger: 'change', message: '请选择客户级别' }],
          source: [{ required: true, trigger: 'change', message: '请选择客户来源' }],
        },
        provinceOptions: [],
        provinceDetail: [],
        industryOptions: [], //客户类型
        levelOptions: [], //客户级别
        sourceOptions: [], //客户来源
      }
    },
    mounted() {
      this.getOptions()
    },
    methods: {
      async init(ids) {
        if (!ids) {
          this.title = '新增客户信息'
          this.editVisible = true
          this.areaEditDisable = false
          return
        }
        this.title = '编辑客户'
        this.areaEditDisable = true
        const [err, res] = await to(api.getDetail({ ids }))
        if (err) return
        if (res.data.list[0]) this.editForm = res.data.list[0]
        else return
        this.editVisible = true
        this.showLocation()
      },
      getOptions() {
        Promise.all([
          api.getProvinceDetail(),
          this.getDicts('cust_level'),
          this.getDicts('cust_idy'),
          this.getDicts('cust_source'),
        ])
          .then(([province, level, industry, source]) => {
            this.provinceOptions = province.data.list || []
            this.levelOptions = level.data.values || []
            this.industryOptions = industry.data.values || []
            this.sourceOptions = source.data.values || []
          })
          .catch((err) => console.log(err))
      },
      // 保存客户
      async customerSave() {
        let params = { ...this.editForm }
        const [valid] = await to(this.$refs.editForm.validate())
        if (valid == false) return
        if (!params.province.id) return this.$message.warning('请选择所在省')
        if (!params.city.id) return this.$message.warning('请选择所在市')
        if (!params.region.id) return this.$message.warning('请选择所在区')
        let arr = []
        arr.push(params.province.distName)
        if (params.city.id) arr.push(params.city.distName)
        if (params.region.id) arr.push(params.region.distName)
        params.custLocation = arr.join('/')
        params.custProvinceId = params.province.id
        params.custProvince = params.province.distName
        params.custCityId = params.city.id
        params.custCity = params.city.distName
        params.custRegionId = params.region.id
        params.custRegion = params.region.distName
        if (!params.followUpDate) params.followUpDate = null
        const [err, res] = await to(api.createCustomer(params))
        if (err) return
        if (res.code == 200) this.$message.success(res.msg)
        else return
        this.editVisible = false
        this.$emit('customerSave')
        return {
          id: res.data.lastId,
          name: params.custName,
        }
      },
      // 编辑客户
      async customerEdit() {
        let params = { ...this.editForm }
        const [valid] = await to(this.$refs.editForm.validate())
        if (valid == false) return
        if (!params.province.id) return this.$message.warning('请选择所在省')
        if (!params.city.id) return this.$message.warning('请选择所在市')
        if (!params.region.id) return this.$message.warning('请选择所在区')
        let arr = []
        arr.push(params.province.distName)
        if (params.city.id) arr.push(params.city.distName)
        if (params.region.id) arr.push(params.region.distName)
        params.custLocation = arr.join('/')
        params.custProvinceId = params.province.id
        params.custProvince = params.province.distName
        params.custCityId = params.city.id
        params.custCity = params.city.distName
        params.custRegionId = params.region.id
        params.custRegion = params.region.distName
        if (!params.followUpDate) params.followUpDate = null
        const [err, res] = await to(api.updateCostomer(params))
        if (err) return
        if (res.code == 200) this.$message.success(res.msg)
        else return
        this.editVisible = false
        this.$emit('customerSave')
      },
      // 联系人弹窗
      async createContact() {
        const res = await this.customerSave()
        if (!res) return
        this.$emit('createContact', res)
      },
      // 省份改变
      async handleProvinceChange(val) {
        const [err, res] = await to(api.getProvinceDetail({ Id: val.id }))
        if (err) return
        this.provinceDetail = res.data.list || []
      },
      handleClose() {
        this.editForm = {
          custName: '', // 客户名称
          abbrName: '', // 助记名
          custLocation: '', // 所在地区
          custAddress: '', // 详细地址
          invoiceHeader: '', // 开票抬头
          custStatus: '', // 客户状态(10正常20)
          followUpDate: '', // 最后跟进时间
          custIndustry: '', // 客户类型  (没数据)
          custLevel: '', // 客户级别  (没数据)
          source: '', //客户来源
          province: {}, //省
          city: {}, //市
          region: {}, //区
        }
        this.$refs.editForm.resetFields()
      },
      showLocation() {
        this.editForm.province = this.provinceOptions.find((item) => item.distName == this.editForm.custProvince)
        this.editForm.city = this.editForm.province.children.find((item) => item.distName == this.editForm.custCity)
        this.editForm.region = this.editForm.city.children.find((item) => item.distName == this.editForm.custRegion)
      },
      provinceChange(val) {
        this.editForm.city = {}
        this.editForm.region = {}
        this.editForm.custDistCode = val.id
        this.$forceUpdate()
      },
      cityChange() {
        this.editForm.region = {}
        this.$forceUpdate()
      },
    },
  }
</script>

<style lang="scss" scoped></style>
