<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"
                disabled
                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"
                    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"
                    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-row>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="单位名称" prop="unit">
              <el-input v-model="form.unit" disabled placeholder="请输入单位名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系人" prop="name">
              <el-input v-model="form.name" disabled placeholder="请输入联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="contact">
              <el-input v-model="form.contact" disabled placeholder="请输入联系方式" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="咨询产品" prop="product">
              <el-input v-model="form.product" disabled placeholder="请输入咨询产品" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="对接人" prop="inchargeName">
              <el-input v-model="form.inchargeName" disabled 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"
            disabled
            maxlength="500"
            resize="none"
            :rows="4"
            show-word-limit
            type="textarea" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="跟进沟通情况" prop="followCommunicateCase">
              <el-select
                v-model="form.followCommunicateCase"
                placeholder="请选择"
                style="width: 100%"
                @change="changeIsProject">
                <el-option label="信息有效，可继续跟进，转C类订单" value="10" />
                <el-option label="信息有效，可转为储备用户" value="20" />
                <el-option label="信息有效，可转为经销商" value="40" />
                <el-option label="信息无效，不再跟进" value="30" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col
            v-if="
              form.followCommunicateCase == '10' ||
              form.followCommunicateCase == '20' ||
              form.followCommunicateCase == '40'
            "
            :span="12">
            <el-form-item v-if="form.followCommunicateCase == '40'" label="关联经销商" prop="distributorName">
              <el-input
                v-model="form.distributorName"
                placeholder="请选择经销商"
                readonly
                suffix-icon="el-icon-search"
                @focus="openDistributor" />
            </el-form-item>
            <el-form-item v-else label="关联项目" prop="nboName">
              <el-input
                v-model="form.nboName"
                placeholder="请选择关联项目"
                readonly
                suffix-icon="el-icon-search"
                @focus="openProject" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="进展描述" prop="progress">
          <el-input v-model="form.progress" maxlength="500" resize="none" :rows="4" show-word-limit type="textarea" />
        </el-form-item>
        <el-form-item label="下一步计划" prop="nextPlan">
          <el-input v-model="form.nextPlan" maxlength="500" resize="none" :rows="4" show-word-limit type="textarea" />
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button type="primary" @click="consultEdit">保存</el-button>
        <el-button @click="visible = false">取消</el-button>
      </span>
    </el-dialog>
    <!-- 选择销售工程师弹窗 -->
    <select-user ref="selectSales" :query-params="{ roles: ['SalesEngineer', 'SalesDirector'] }" @save="selectSales" />
    <!-- 客户 -->
    <select-customer ref="selectCustomer" @save="selectCustomer" />
    <!-- 选择项目 -->
    <select-business ref="project" :multiple="false" @save="getBusinessInfo" />
    <!-- 选择渠道弹窗 -->
    <select-distributor ref="selectDistributor" @save="selectDistributor" />
  </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 SelectCustomer from '@/components/select/SelectCustomer'
  import SelectBusiness from '@/components/select/SelectBusiness'
  import SelectDistributor from '@/components/select/SelectDistributor'

  export default {
    components: { SelectUser, SelectCustomer, SelectBusiness, SelectDistributor },
    data() {
      return {
        title: '',
        visible: false,
        areaEditDisable: true,
        provinceOptions: [],
        currentProvince: [],
        form: {
          id: 0,
          code: '', // 序号
          consultTime: null, // 日期时间
          provinceId: 0, // 所在省ID
          province: '', // 所在省
          cityId: 0, // 所在市ID
          city: '', // 所在市
          unit: '', // 单位名称
          name: '', // 联系人
          contact: '', // 联系方式
          product: '', // 咨询产品
          inchargeId: '', // 对接人ID
          inchargeName: '', // 对接人(销售工程师)
          content: '', // 内容
          progress: '', // 进展描述
          nextPlan: '', // 下一步计划
          custId: 0, // 客户ID
          custName: '', // 客户
          nboId: 0, // 关联项目
          nboName: '', // 项目名称,
          distributorId: 0, // 经销商
          distributorName: '', // 经销商
          followCommunicateCase: '', // 10、信息有效，可继续跟进，转C类订单；20、信息有效，可转为储备用户；30、信息无效，不再跟进。
        },
        rules: {
          followCommunicateCase: [{ required: true, trigger: ['blur', 'change'], message: '请选择跟进沟通情况' }],
          nboName: [{ required: true, trigger: ['blur', 'change'], message: '请选择项目' }],
          progress: [{ required: true, trigger: ['blur', 'change'], message: '不能为空' }],
          nextPlan: [{ required: true, trigger: ['blur', 'change'], message: '不能为空' }],
          distributorName: [{ 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 consultEdit() {
        this.$refs.form.validate(async (valid) => {
          if (valid) {
            let params = { ...this.form }
            const [err, res] = await to(consultApi.followUp(params))
            if (err) return
            this.$message.success(res.msg)
            this.visible = false
            this.$emit(
              'consultSave',
              this.form.followCommunicateCase == '10' || this.form.followCommunicateCase == '20'
            )
          }
        })
      },
      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()
      },
      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()
      },
      handleSelectCustomer() {
        this.$refs.selectCustomer.open()
      },
      selectCustomer(val) {
        this.form.custId = 0
        this.form.custName = ''
        if (val && val.length > 0) {
          this.form.custId = val[0].id
          this.form.custName = val.map((item) => item.custName).join()
        }
      },
      close() {
        this.form = {
          id: 0,
          code: '', // 序号
          consultTime: null, // 日期时间
          provinceId: 0, // 所在省ID
          province: '', // 所在省
          cityId: 0, // 所在市ID
          city: '', // 所在市
          unit: '', // 单位名称
          name: '', // 联系人
          contact: '', // 联系方式
          product: '', // 咨询产品
          inchargeId: '', // 对接人ID
          inchargeName: '', // 对接人(销售工程师)
          content: '', // 内容
          progress: '', // 进展描述
          nextPlan: '', // 下一步计划
          custId: 0, // 客户ID
          custName: '', // 客户
          nboId: 0, // 关联项目
          nboName: '', // 项目名称
          distributorId: 0, // 经销商
          distributorName: '', // 经销商
          followCommunicateCase: '', // 10、信息有效，可继续跟进，转C类订单；20、信息有效，可转为储备用户；30、信息无效，不再跟进。
        }
        this.$refs['form'].resetFields()
      },
      changeIsProject() {
        this.form.nboId = 0
        this.form.nboName = ''
        this.form.distributorId = 0
        this.form.distributorName = ''
      },
      // 打开选择项目
      openProject() {
        this.$refs.project.open()
      },
      openDistributor() {
        this.$refs.selectDistributor.open()
      },
      // 关闭选择项目获取项目信息
      getBusinessInfo(data) {
        this.form.nboId = 0
        this.form.nboName = ''
        let business = data[0] || null
        if (!business) return
        this.form.nboId = business.id
        this.form.nboName = business.nboName
      },
      selectDistributor(data) {
        this.form.distributorId = 0
        this.form.distributorName = ''
        let distributor = data[0] || null
        if (!distributor) return
        this.form.distributorId = distributor.id
        this.form.distributorName = distributor.distName
      },
    },
  }
</script>

<style></style>
