<template>
  <el-dialog :visible.sync="editVisible"
             @close="handleClose"
             :title="title">
    <el-form ref="editForm"
             :model="editForm"
             :rules="editRules">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="客户名称"
                        prop="custName">
            <el-input placeholder="请输入客户名称"
                      v-model="editForm.custName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="助记名"
                        prop="abbrName">
            <el-input placeholder="请输入助记名"
                      v-model="editForm.abbrName"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="客户行业"
                        prop="custIndustry">
            <el-select style="width:100%"
                       placeholder="请选择客户行业"
                       v-model="editForm.custIndustry">
              <el-option v-for="item in industryOptions"
                         :key="item.value"
                         :label="item.value"
                         :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户级别"
                        prop="custLevel">
            <el-select style="width:100%"
                       placeholder="请选择客户级别"
                       v-model="editForm.custLevel">
              <el-option v-for="item in levelOptions"
                         :key="item.value"
                         :label="item.value"
                         :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="客户来源"
                        prop="source">
            <el-select style="width:100%"
                       placeholder="请选择客户来源"
                       v-model="editForm.source">
              <el-option v-for="item in sourceOptions"
                         :key="item.value"
                         :label="item.value"
                         :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="下次联系时间"
                        prop="followUpDate">
            <el-date-picker style="width:100%"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="选择下次联系时间"
                            v-model="editForm.followUpDate">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所在地区"
                        required>
            <el-row style="width:100%;padding-top:32px"
                    :gutter="4">
              <el-col :span="8">
                <el-select placeholder="省"
                           value-key="id"
                           @change="provinceChange"
                           v-model="editForm.province">
                  <el-option v-for="item in provinceOptions"
                             :key="item.id"
                             :label="item.distName"
                             :value="item"></el-option>
                </el-select>
              </el-col>
              <el-col :span="8">
                <el-select placeholder="市"
                           value-key="id"
                           @change="cityChange"
                           v-model="editForm.city">
                  <el-option v-for="item in (editForm.province ? editForm.province.children : [])"
                             :key="item.id"
                             :label="item.distName"
                             :value="item"></el-option>
                </el-select>
              </el-col>
              <el-col :span="8">
                <el-select placeholder="区"
                           value-key="id"
                           @change="$forceUpdate()"
                           v-model="editForm.region">
                  <el-option v-for="item in (editForm.city ? editForm.city.children : [])"
                             :key="item.id"
                             :label="item.distName"
                             :value="item"></el-option>
                </el-select>
              </el-col>
            </el-row>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="详细地址"
                        prop="custAddress">
            <el-input placeholder="请输入详细地址"
                      v-model="editForm.custAddress"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注"
                    prop="remark">
        <el-input type="textarea"
                  placeholder="请输入备注"
                  v-model="editForm.remark"
                  resize="none"
                  :rows="5"
                  maxlength="500"
                  show-word-limit></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer">
      <el-button type="primary"
                 @click="customerSave"
                 v-show="!editForm.id">保存</el-button>
      <el-button type="primary"
                 @click="customerEdit"
                 v-show="editForm.id">保存</el-button>
      <el-button @click="createContact"
                 v-if="!editForm.id">保存并新建联系人</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 () {
    return {
      title: '新增客户信息',
      // 新增编辑客户弹窗
      editVisible: false,
      editForm: {
        custName: '',    // 客户名称
        abbrName: '',     // 助记名
        custLocation: '', // 所在地区
        custAddress: '',  // 详细地址
        custStatus: '',   // 客户状态(10正常20)
        followUpDate: '', // 最后跟进时间
        custIndustry: '',  // 客户行业  (没数据)
        custLevel: '',    // 客户级别  (没数据)
        source: '',//客户来源
        province: '',//省
        city: '',//市
        region: '', //区
      },
      editRules: {
        custName: [{ required: true, trigger: 'blur', message: '请输入客户名称' }],
        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
        return
      }
      this.title = '编辑客户'
      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('CustomerLevel'),
        this.getDicts('CustomerIndustry'),
        this.getDicts('CustomerSource'),
      ]).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('请选择所在地区')
      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('/')
      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('请选择所在地区')
      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('/')
      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: '',  // 详细地址
        custStatus: '',   // 客户状态(10正常20)
        followUpDate: '', // 最后跟进时间
        custIndustry: '',  // 客户行业  (没数据)
        custLevel: '',    // 客户级别  (没数据)
        source: '',//客户来源
        province: '',//省
        city: '',//市
        region: '', //区
      }
      this.$refs.editForm.resetFields()
    },
    showLocation () {
      const arr = this.editForm.custLocation.split('/')
      console.log(arr, 'arr');
      if (!arr.length) return
      this.editForm.province = this.provinceOptions.find(item => item.distName == arr[0])
      if (arr[1]) this.editForm.city = this.editForm.province.children.find(item => item.distName == arr[1])
      if (arr[2]) this.editForm.region = this.editForm.city.children.find(item => item.distName == arr[2])
    },
    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>