<template>
  <div class="customer-follow">
    <el-dialog append-to-body :title="$t('客户跟进')" :visible.sync="customerFollow.dialogVisible" :close-on-click-modal="false" :close-on-press-escape="false" :before-close="customerFollowClose" width="1200px">
      <el-form class="custom-form-1" ref="customerFollowForm" :model="form" label-width="120px">
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item :label="$t('编号')" prop="number">
              <el-input v-model="form.number" :placeholder="$t('请输入编号')" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <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="8">
            <el-form-item :label="$t('客户编号')">
              <el-input v-model="form.customerNumber" :placeholder="$t('请输入客户编号')" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('跟进类型')" required>
              <el-select v-model="form.followType" clearable :placeholder="$t('请选择')" @change="handleFollowType" :disabled="isView || !!offerId">
                <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="8" v-if="form.followType == 2">
            <el-form-item :label="$t('报价单')" required prop="offerId">
              <el-input :value="form.offerNumber" readonly>
                <el-button slot="append" icon="el-icon-search" @click="CustomerFollowSelectOffer = true" v-if="!(isView || offerId)"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <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="8" 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="8" v-else>
            <el-form-item :label="$t('联系人')" required>
              <div class="contact">
                <el-input v-model="form.contactName" placeholder="" disabled />
                <img src="@/assets/svg/contacts.svg" class="phonebook" @click="ChooseContactDialog = true" />
              </div>
            </el-form-item>
          </el-col>

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

          <el-col :span="8">
            <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="8">
            <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="8">
            <el-form-item :label="$t('上一级跟进单')" prop="parentNumber">
              <el-input v-model="form.parentNumber" :placeholder="$t('请输入上一级跟进单')" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('销售阶段')" prop="saleStage">
              <el-select v-model="form.saleStage" clearable :placeholder="$t('请选择')" :disabled="isView">
                <el-option v-for="dict in getDictDatas(DICT_TYPE.CUSTOMER_FOLLOWUP_SALE_STAGE)" :key="dict.value" :label="isChinese ? dict.label : dict.labelEn" :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
<!--          <el-col :span="8">-->
<!--            <el-form-item :label="$t('跟进结果')" prop="resultType">-->
<!--              <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="24">
            <el-form-item :label="$t('目的')" prop="purpose">
              <el-input type="textarea" :rows="3" v-model="form.purpose" :placeholder="$t('请输入目的')" maxlength="200" show-word-limit :disabled="isView" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <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="24">
            <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="24">
            <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="24" 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>-->
                <el-button size="mini" type="text" icon="el-icon-collection" @click="handleUpdate(form, true)" v-has-permi="['ecw:customer:follow-add-plan']">{{ $t("增加计划") }} </el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <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="8">
            <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="8">
            <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="8">
            <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" />
    <CustomerFollowSelectOffer v-if="CustomerFollowSelectOffer" :customer-id="customerId" ref="customerFollowSelectOffer" @select="selectOffer" @close="CustomerFollowSelectOffer = 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 { addCustomerFollow, editCustomerFollow, getFollowupNewNumber } from "@/api/ecw/customerFollow"
import { getCustomerContactsSelect } from "@/api/ecw/customerContacts"
import { getOfferPage, getOfferNumber, getOffer } 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"
import CustomerFollowSelectOffer from "./customerFollowSelectOffer"
export default {
  /**
   * 客户跟进
   * 客户投诉跟进
   */
  name: "CustomerFollow",
  props: {
    /**
     * 如果是客户投诉跟进，则id为客户投诉id；如果是客户跟进，则id为客户id
     */
    offerId: Number,
    customerId: Number,
    customerNumber: String,
    customerService: Number
  },
  components: {
    ChooseContactDialog,
    CustomerFollowSelectOffer,
    FileUpload
  },
  data() {
    return {
      CustomerFollowSelectOffer: false,
      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: {
        offerId: undefined
      },
      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
    })
  },
  watch: {
    "form.offerId"(v) {
      if (v) {
        getOffer(v).then((r) => {
          let offer = r.data
          // 选择了报价单后，需要将报价单中的客户及客户联系人信息回显
          this.form.offerNumber = offer.number
          this.form.customerId = offer.relationId
          this.customerId = offer.relationId
          this.form.contactId = offer.relation === 1 ? offer.consignorId : offer.consigneeId
          getCustomerContactsListByCustomer({
            customerId: this.form.customerId
          }).then((res) => {
            this.customerContactsList = res.data
            this.customerContactsList.forEach((item) => {
              if (item.id === this.form.contactId) {
                this.form.customerNumber = item.customerNumber
                this.form.contactName = item.name
                this.form.contactPhone = "+" + item.areaCode + item.phoneNew
                this.form.followUserId = item.customerService
              }
            })
          })
        })
      } else {
        this.form.offerNumber = ""
      }
    },
    "form.customerId"(v) {
      if (v) {
        getCustomerContactsListByCustomer({
          customerId: v
        }).then((res) => {
          this.customerContactsList = res.data
          this.customerContactsList.forEach((item) => {
            if (item.id === this.form.contactId) {
              this.form.customerNumber = item.customerNumber
              this.form.contactName = item.name
              this.form.contactPhone = "+" + item.areaCode + item.phoneNew
              this.form.followUserId = item.customerService
            }
          })
          if (!this.form.contactId) {
            this.customerContactsList.some((item) => {
              if (item.isDefault) {
                this.form.contactId = item.id
                this.form.customerNumber = item.customerNumber
                this.form.contactName = item.name
                this.form.contactPhone = "+" + item.areaCode + item.phoneNew
                this.form.followUserId = item.customerService
                return true
              }
            })
          }
        })
      } else {
        this.form.customerNumber = ""
      }
    }
  },
  methods: {
    selectOffer(offerId) {
      this.form.offerId = offerId
    },
    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.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.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) {
      } 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: this.offerId ? 2 : undefined,
        followUserId: this.customerService,
        nextPlan: undefined,
        nextTime: undefined,
        number: undefined,
        offerId: this.offerId,
        offerNumber: undefined,
        parentId: undefined,
        parentNumber: undefined,
        purpose: undefined,
        saleStage: 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 (this.form.followType === 2 && !this.form.offerId) {
          this.$modal.msgError(this.$t("请选择报价单"))
          return
        }

        if (status === 0) {
          this.saveSubmitData(status)
        } else {
          // 提交结果时，除了附件和上级跟进单为非必填，其他都是必填
          if (!this.form.customerId) {
            this.$modal.msgError(this.$t("请选择客户"))
            return
          }
          if (!this.form.contactId) {
            this.$modal.msgError(this.$t("请选择客户联系人"))
            return
          }
          // if (!this.form.resultType) {
          //   this.$modal.msgError(this.$t("请选择跟进结果"))
          //   return
          // }
          if (!this.form.purpose) {
            this.$modal.msgError(this.$t("请填写跟进目的"))
            return
          }
          if (!this.form.feedback) {
            this.$modal.msgError(this.$t("请填写跟进情况"))
            return
          }
          if (!this.form.nextTime) {
            this.$modal.msgError(this.$t("请选择下次跟进时间"))
            return
          }
          if (!this.form.nextPlan) {
            this.$modal.msgError(this.$t("请填写下一步计划"))
            return
          }
          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
      this.$emit("close")
    },
    handleView(row) {
      this.form = row
      this.isView = this.form.status === 1
      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,
          purpose: row.nextPlan,
          followTime: row.nextTime,
          nextTime: "",
          number: r.data.number,
          numberId: r.data.numberId,
          numberVersion: r.data.numberVersion,
          nextPlan: "",
          status: 0
        }
      }
      this.init()
    }
  }
}
</script>

<style scoped lang="scss">
.border {
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  ::v-deep .el-textarea__inner {
    padding: 0 4px;
    border: 0;
  }
}
.text_style {
  white-space: pre-wrap;
}
</style>
