<template>
  <div>
    <el-dialog append-to-body :title="title" :visible.sync="visible" @close="close">
      <el-form ref="form" :model="form" :rules="rules">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="序号" prop="code">
              <el-input v-model="form.code" disabled :placeholder="form.code ? form.code : '自动生成无需填写'" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="日期时间" prop="consultTime">
              <el-date-picker
                v-model="form.consultTime"
                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="所在地区" required>
              <el-row :gutter="4" style="width: 100%; padding-top: 32px">
                <el-col :span="8">
                  <el-select
                    v-model="form.province"
                    :disabled="areaEditDisable"
                    filterable
                    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="form.city"
                    :disabled="areaEditDisable"
                    filterable
                    placeholder="市"
                    value-key="id"
                    @change="cityChange">
                    <el-option
                      v-for="item in currentProvince ? currentProvince.children : []"
                      :key="item.id"
                      :label="item.distName"
                      :value="item" />
                  </el-select>
                </el-col>
                <el-col :span="8">
                  <el-button :disabled="areaEditDisable" type="primary" @click="showSelectCityDialog">搜索</el-button>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位名称" prop="unit">
              <el-input v-model="form.unit" placeholder="请输入单位名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="4" style="width: 100%; padding-top: 32px">
          <el-col :span="12">
            <el-form-item label="联系人" prop="name">
              <el-input v-model="form.name" placeholder="请输入联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="contact">
              <el-input v-model="form.contact" placeholder="请输入联系方式" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="咨询产品" prop="product">
              <el-input v-model="form.product" placeholder="请输入咨询产品" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="对接人" prop="inchargeName">
              <el-input v-model="form.inchargeName" suffix-icon="el-icon-search" @focus="handleSelectSale" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="400电话内容" prop="content">
          <el-input v-model="form.content" maxlength="500" resize="none" :rows="5" show-word-limit type="textarea" />
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button v-show="form.id" type="primary" @click="consultEdit">保存</el-button>
        <el-button v-show="!form.id" type="primary" @click="consultSave">保存</el-button>
        <el-button @click="visible = false">取消</el-button>
      </span>
    </el-dialog>
    <!-- 选择销售工程师弹窗 -->
    <select-user
      ref="selectSales"
      :query-params="{
        roles: ['SalesEngineer', 'SalesDirector', 'StrategicProjectTeamLeader', 'StrategicProjectTeam'],
      }"
      @save="selectSales" />
    <!-- 地区搜索 -->
    <selectCity ref="selectCity" @submit="submitCity" />
  </div>
</template>

<script>
  import to from 'await-to-js'
  import customerApi from '@/api/customer'
  import consultApi from '@/api/consult'
  import SelectUser from '@/components/select/SelectUser'
  import selectCity from './selectCity'

  export default {
    components: { SelectUser, selectCity },
    data() {
      return {
        title: '',
        visible: false,
        areaEditDisable: false,
        provinceOptions: [],
        currentProvince: [],
        form: {
          id: 0,
          code: '', // 序号
          consultTime: null, // 日期时间
          provinceId: 0, // 所在省ID
          province: '', // 所在省
          cityId: 0, // 所在市ID
          city: '', // 所在市
          unit: '', // 单位名称
          name: '', // 联系人
          contact: '', // 联系方式
          product: '', // 咨询产品
          inchargeId: '', // 对接人ID
          inchargeName: '', // 对接人(销售工程师)
          content: '', // 内容
        },
        rules: {
          code: [{ required: false }],
          consultTime: [{ required: true, trigger: ['blur', 'change'], message: '请输入日期时间' }],
          provinceId: [{ required: true, trigger: ['blur', 'change'], message: '请输入所在省ID' }],
          province: [{ required: true, trigger: ['blur', 'change'], message: '请输入所在省' }],
          cityId: [{ required: true, trigger: ['blur', 'change'], message: '请输入所在市ID' }],
          city: [{ required: true, trigger: ['blur', 'change'], message: '请输入所在市' }],
          unit: [{ required: true, trigger: ['blur', 'change'], message: '请输入单位名称' }],
          name: [{ required: true, trigger: ['blur', 'change'], message: '请输入联系人' }],
          contact: [{ required: true, trigger: ['blur', 'change'], message: '请输入联系方式' }],
          product: [{ required: true, trigger: ['blur', 'change'], message: '请输入咨询产品' }],
          inchargeId: [{ required: true, trigger: ['blur', 'change'], message: '请输入对接人ID' }],
          inchargeName: [{ required: true, trigger: ['blur', 'change'], message: '请输入对接人' }],
          content: [{ required: true, trigger: ['blur', 'change'], message: '请输入内容' }],
        },
      }
    },
    mounted() {
      Promise.all([customerApi.getProvinceDetail()])
        .then(([province]) => {
          this.provinceOptions = province.data.list || []
        })
        .catch((err) => console.log(err))
    },
    methods: {
      async init(id) {
        this.visible = true
        if (!id) {
          this.title = '新建咨询记录'
          return
        }
        this.title = '编辑咨询记录'
        const [err, res] = await to(consultApi.get({ id: id }))
        if (err) return
        this.form = res.data
      },
      // 保存
      async consultSave() {
        this.$refs.form.validate(async (valid) => {
          if (valid) {
            let params = { ...this.form }
            const [err, res] = await to(consultApi.add(params))
            if (err) return
            this.$message.success(res.msg)
            this.visible = false
            this.$emit('consultSave')
          }
        })
      },
      async consultEdit() {
        this.$refs.form.validate(async (valid) => {
          if (valid) {
            let params = { ...this.form }
            const [err, res] = await to(consultApi.update(params))
            if (err) return
            this.$message.success(res.msg)
            this.visible = false
            this.$emit('consultSave')
          }
        })
      },
      provinceChange(val) {
        this.currentProvince = val
        this.form.provinceId = val.id
        this.form.province = val.distName
        this.form.cityId = 0
        this.form.city = ''
        this.$forceUpdate()
      },
      cityChange(val) {
        this.form.cityId = val.id
        this.form.city = val.distName
        this.$forceUpdate()
      },
      // 打开选择城市弹窗
      showSelectCityDialog() {
        this.$refs.selectCity.openDialog()
      },
      // 选中城市
      submitCity(row) {
        this.form.provinceId = row.provinceId
        this.form.province = row.province
        this.form.cityId = row.cityId
        this.form.city = row.city
        for (let item of this.provinceOptions) {
          if (item.id == row.provinceId) {
            this.currentProvince = item
            break
          }
        }
      },
      selectSales(val) {
        if (val && val.length > 0) {
          this.form.inchargeId = val[0].id
          this.form.inchargeName = val.map((item) => item.nickName).join()
        }
      },
      handleSelectSale() {
        this.$refs.selectSales.open()
      },
      close() {
        this.form = {
          id: 0,
          code: '', // 序号
          consultTime: null, // 日期时间
          provinceId: 0, // 所在省ID
          province: '', // 所在省
          cityId: 0, // 所在市ID
          city: '', // 所在市
          unit: '', // 单位名称
          name: '', // 联系人
          contact: '', // 联系方式
          product: '', // 咨询产品
          inchargeId: '', // 对接人ID
          inchargeName: '', // 对接人(销售工程师)
          content: '', // 内容
        }
        this.$refs['form'].resetFields()
      },
    },
  }
</script>

<style></style>
