<template>
  <div class="customer-follow">
    <el-dialog append-to-body :title="$t('客户跟进')" :visible.sync="customerFollow.dialogVisible" :before-close="customerFollowClose" width="900px">
      <el-form ref="customerFollowForm" :model="form" label-width="120px">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item :label="$t('编号')" prop="number">
              <el-input v-model="form.number" :placeholder="$t('请输入编号')" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('跟进状态')">
              <el-select v-model="form.status" :placeholder="$t('请选择')" disabled>
                <el-option v-for="dict in getDictDatas(DICT_TYPE.CUSTOMER_FOLLOWUP_STATUS)" :key="dict.value" :label="isChinese ? dict.label : dict.labelEn" :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('客户编号')">
              <el-input v-model="form.customerNumber" :placeholder="$t('请输入客户编号')" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('跟进类型')" required>
              <el-select v-model="form.followType" clearable :placeholder="$t('请选择')" @change="handleFollowType" :disabled="isView">
                <el-option v-for="dict in getDictDatas(DICT_TYPE.CUSTOMER_FOLLOWUP_TYPE)" :key="dict.value" :label="isChinese ? dict.label : dict.labelEn" :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('跟进时间')" required>
              <el-date-picker v-model="form.followTime" clearable type="datetime" :placeholder="$t('请选择')" :disabled="isView" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="customerId">
            <el-form-item :label="$t('联系人')" required>
              <el-select v-model="form.contactId" clearable :placeholder="$t('请选择')" :disabled="isView" @change="changeContactUser">
                <el-option v-for="(item, index) in customerContactsList" :key="index" :label="item.name" :value="item.id"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-else>
            <el-form-item :label="$t('联系人')" required>
              <div class="contact">
                <el-input v-model="form.contactName" :value="form.customerContactsId" placeholder="" disabled />
                <img src="@/assets/svg/contacts.svg" class="phonebook" @click="ChooseContactDialog = true" />
              </div>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item :label="$t('联系方式')">
              <el-input v-model="form.contactPhone" disabled />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item :label="$t('客户经理')" required>
              <el-select v-model="form.followUserId" clearable :placeholder="$t('请选择')" :disabled="isView">
                <el-option v-for="item in serviceUserList" :key="item.id" :label="item.nickname" :value="item.id"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('跟进方式')" required>
              <dict-selector ref="dictMethod" v-model="form.followMethod" clearable :disabled="isView" :type="DICT_TYPE.CUSTOMER_FOLLOWUP_METHOD"></dict-selector>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('上一级跟进单')" prop="parentNumber">
              <el-input v-model="form.parentNumber" :placeholder="$t('请输入上一级跟进单')" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('跟进结果')" prop="followMethod">
              <el-select v-model="form.resultType" clearable :placeholder="$t('请选择')" :disabled="isView">
                <el-option v-for="dict in getDictDatas(DICT_TYPE.CUSTOMER_FOLLOWUP_RESULT_TYPE)" :key="dict.value" :label="isChinese ? dict.label : dict.labelEn" :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item :label="$t('目的')" prop="purpose">
              <el-input type="textarea" :rows="2" v-model="form.purpose" :placeholder="$t('请输入目的')" maxlength="200" show-word-limit :disabled="isView" />
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item :label="$t('跟进情况')">
              <el-input rows="3" class="text_style" type="textarea" v-model="form.feedback" maxlength="500" show-word-limit :disabled="isView" />
            </el-form-item>
          </el-col>
          <el-col :span="20" v-if="isView">
            <el-form-item>
              <div style="text-align: right">
                <el-button size="mini" icon="el-icon-collection" type="primary" @click="$emit('handleCustomerFollowAdd', form)" v-has-permi="['ecw:customer:follow-add-plan']">{{ $t("增加计划") }} </el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item :label="$t('附件')" prop="attatchment">
              <FileUpload :limit="5" :isShowTip="true" v-model="form.attatchment" :fileType="fileType" :disabled="isView" />
            </el-form-item>
          </el-col>
          <el-col :span="13">
            <el-form-item :label="$t('下次跟进时间')">
              <el-date-picker v-model="form.nextTime" type="datetime" :placeholder="$t('请选择')" :disabled="isView" @change="changeNextTime"> </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item :label="$t('下一步计划')" prop="nextPlan">
              <el-input type="textarea" :rows="3" v-model="form.nextPlan" :placeholder="$t('请输入下一步计划')" maxlength="500" show-word-limit :disabled="isView" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('创建人')" prop="founder">
              <el-select v-model="form.creatorName" disabled :placeholder="$t('请选择')">
                <el-option v-for="item in allSimplList" :key="item.id" :label="item.nickname" :value="item.id"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('创建时间')" prop="createTime">
              <el-date-picker v-model="form.createTime" type="datetime" disabled :placeholder="$t('请选择')"> </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('最后更新人')">
              <el-select v-model="form.updaterName" disabled>
                <el-option v-for="item in allSimplList" :key="item.id" :label="item.nickname" :value="item.id"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('最后更新时间')">
              <el-date-picker v-model="form.updateTime" type="datetime" disabled :placeholder="$t('请选择')"> </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="isView">
        <el-button type="warning" @click="customerFollowClose">{{ $t("关 闭") }}</el-button>
      </div>
      <div slot="footer" class="dialog-footer" v-else>
        <el-button type="warning" @click="goBack">{{ $t("返 回") }}</el-button>
        <el-button type="primary" @click="customerFollowSubmit(0)">{{ $t("保 存") }}</el-button>
        <el-button type="success" @click="customerFollowSubmit(1)">{{ $t("提交结果") }}</el-button>
      </div>
    </el-dialog>
    <choose-contact-dialog v-if="ChooseContactDialog" :type="2" @choose="changeAllContactUser" @close="ChooseContactDialog = false" />
  </div>
</template>
<style lang="scss" scoped>
.contact {
  display: flex;
  align-items: center;
  justify-content: center;
  img.phonebook {
    width: 30px;
    height: 30px;
    margin-left: 10px;
    cursor: pointer;
  }
}
</style>
<script>
import { createCustomerFollow, getCustomerFollowPage, getCustomerFollowPage2, addCustomerFollow, getCustomerFollowList, editCustomerFollow, getFollowupNewNumber } from "@/api/ecw/customerFollow"
import { getCustomerContactsSelect } from "@/api/ecw/customerContacts"
import { getOfferPage } from "@/api/ecw/offer"
import { DICT_TYPE, getDictDataLabel } from "@/utils/dict"
import { getCustomerContactsListByCustomer } from "@/api/ecw/customerContacts"
import { listAllSimpl, listServiceUser, listSimpleUsers } from "@/api/system/user"
import { parseTime } from "@/utils/ruoyi"
import FileUpload from "@/components/FileUpload/fileUpload"
import { formatDate } from "@/utils/index"
import ChooseContactDialog from "@/components/ChooseContactDialog"
export default {
  /**
   * 客户跟进
   * 客户投诉跟进
   */
  name: "CustomerFollow",
  props: {
    /**
     * 如果是客户投诉跟进，则id为客户投诉id；如果是客户跟进，则id为客户id
     */
    customerId: Number,
    customerNumber: String,
    customerService: Number
  },
  components: {
    ChooseContactDialog,
    FileUpload
  },
  data() {
    return {
      ChooseContactDialog: false,
      fileType: ["doc", "xls", "ppt", "txt", "pdf", "png", "jpg", "jpeg"],
      DICT_TYPE,
      getDictDataLabel,
      parseTime,
      customerFollowList: [],
      serviceUserList: [],
      customerContactsList: [],
      customerFollow: {
        dialogVisible: false,
        form: {
          followType: "3"
        }
      },
      offerDialogVisible: true,
      form: {},
      pageNo: 1,
      pageSize: 10,
      total: 10,
      allSimplList: [],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() <= Date.now()
        }
      },
      followTime: [],
      nextTime: [],
      queryParams: {
        pageNo: 1,
        pageSize: 10
      },
      offerList: [],
      offerTotal: 0,
      isView: false
    }
  },
  computed: {
    isChinese() {
      return this.$i18n.locale === "zh_CN"
    }
  },
  created() {
    listServiceUser().then((r) => {
      this.serviceUserList = r.data
    })
    listAllSimpl().then((r) => {
      this.allSimplList = r.data
    })
  },
  methods: {
    init() {
      if (this.form.customerId) {
        getCustomerContactsListByCustomer({
          customerId: this.form.customerId
        }).then((r) => {
          this.customerContactsList = r.data
        })
      } else {
        getCustomerContactsSelect().then((res) => {
          this.customerContactsList = res.data.list.map((item) => {
            return {
              name: item.contactsName,
              id: item.customerContactsId,
              customerId: item.customerId,
              phoneNew: item.phoneNew,
              areaCode: item.areaCode,
              customerNumber: item.customerNumber
            }
          })
        })
      }
    },
    changeAllContactUser(item) {
      console.log(item)

      if (item) {
        this.form.contactId = item.customerContactsId
        this.form.contactName = item.contactsName
        this.form.customerId = item.customerId
        this.form.contactPhone = "+" + item.areaCode + item.phoneNew
        if (item.customerService) this.form.followUserId = item.customerService
        if (item.customerNumber) this.form.customerNumber = item.customerNumber
      } else {
        this.form.contactId = null
        this.form.contactName = null
        this.form.contactPhone = null
      }
      this.ChooseContactDialog = false
    },
    changeContactUser(val) {
      if (val) {
        for (const item of this.customerContactsList) {
          if (item.id == val) {
            this.form.contactId = item.id
            this.form.contactName = item.name
            this.form.customerId = item.customerId
            this.form.contactPhone = "+" + item.areaCode + item.phoneNew
            if (item.customerService) this.form.followUserId = item.customerService
            if (item.customerNumber) this.form.customerNumber = item.customerNumber
            break
          }
        }
      } else {
        this.form.contactName = null
        this.form.contactPhone = null
      }
    },
    getOfferList() {
      getOfferPage(this.queryParams).then((response) => {
        this.offerList = response.data.list
        this.offerTotal = response.data.total
      })
    },
    handleFollowType(val) {
      console.log(val)
      if (val == "2") {
        this.$refs["customerFollowSelectOffer"].offerDialogVisible = true
      } else {
        this.form.offerId = undefined
      }
    },
    reset() {
      this.form = {
        attatchment: undefined,
        contactId: undefined,
        contactName: undefined,
        contactPhone: undefined,
        customerId: this.customerId,
        customerNumber: this.customerNumber,
        feedback: undefined,
        followMethod: undefined,
        followTime: new Date().getTime(),
        followType: undefined,
        followUserId: this.customerService,
        nextPlan: undefined,
        nextTime: undefined,
        number: undefined,
        offerId: undefined,
        parentId: undefined,
        parentNumber: undefined,
        purpose: undefined,
        resultType: undefined,
        status: undefined,
        creatorName: this.$store.getters.userId,
        createTime: new Date().getTime(),
        updaterName: this.$store.getters.userId,
        updateTime: new Date().getTime()
      }
    },
    changeNextTime(val) {
      if (val) {
        const curTime = new Date().getTime()
        const valTime = new Date(val).getTime()
        if (curTime > valTime) {
          this.form.nextTime = null
          this.$modal.msgError(this.$t("不能小于当前时间"))
        }
      }
    },
    customerFollowSubmit(status) {
      console.log(this.form)
      this.$refs["customerFollowForm"].validate((valid) => {
        if (!valid) {
          return
        }
        if (!this.form.followType) {
          this.$modal.msgError(this.$t("请选择跟进类型"))
          return
        }
        if (!this.form.followTime) {
          this.$modal.msgError(this.$t("请选择跟进时间"))
          return
        }
        if (!this.form.contactName) {
          this.$modal.msgError(this.$t("请选择联系人"))
          return
        }
        if (!this.form.followUserId) {
          this.$modal.msgError(this.$t("请选择客户经理"))
          return
        }
        if (!this.form.followMethod) {
          this.$modal.msgError(this.$t("请选择跟进方式"))
          return
        }

        if (status === 0) {
          this.saveSubmitData(status)
        } else {
          this.$confirm(this.$t("提交后无法修改"), this.$t("提示"), {
            confirmButtonText: this.$t("确定"),
            cancelButtonText: this.$t("取消"),
            type: "warning"
          }).then(() => {
            this.saveSubmitData(status)
          })
        }
      })
    },
    saveSubmitData(status) {
      let func = this.form.id ? editCustomerFollow : addCustomerFollow
      func({
        ...this.form,
        followTime: this.form.followTime ? formatDate(this.form.followTime) : undefined,
        nextTime: this.form.nextTime ? formatDate(this.form.nextTime) : undefined,
        status
      }).then((r) => {
        this.$message.success(this.$t("操作成功"))
        this.$emit("refresh")
        this.customerFollowClose()
      })
    },
    goBack() {
      this.$confirm(this.$t("是否确认不保存信息"), this.$t("提示"), {
        confirmButtonText: this.$t("确定"),
        cancelButtonText: this.$t("取消"),
        type: "warning"
      }).then(() => {
        this.customerFollowClose()
      })
    },
    customerFollowClose() {
      this.customerFollow.dialogVisible = false
    },
    handleView(row) {
      this.isView = true
      this.form = row
      this.customerFollow.dialogVisible = true
    },
    async handleAdd() {
      this.isView = false
      this.customerFollow.dialogVisible = true
      this.reset()
      let r = await getFollowupNewNumber()
      console.log(r)
      this.form.customerId = this.customerId
      this.form.number = r.data.number
      this.form.numberId = r.data.numberId
      this.form.numberVersion = r.data.numberVersion
      this.form.status = 0
      this.init()
    },
    async handleUpdate(row, flag) {
      this.isView = false
      this.customerFollow.dialogVisible = true
      if (!flag) {
        this.form = row
      } else {
        let r = await getFollowupNewNumber()
        console.log(r)

        this.form = {
          ...row,
          id: null,
          parentNumber: row.number,
          followTime: row.nextTime,
          nextTime: "",
          number: r.data.number,
          numberId: r.data.numberId,
          numberVersion: r.data.numberVersion,
          nextPlan: "",
          status: 0
        }
      }
      this.init()
    }
  }
}
</script>

<style scoped>
.text_style {
  white-space: pre-wrap;
}
</style>
