<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="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="13">
          <el-form-item :label="$t('报价单')">
            <el-input v-model="form.offerId" :placeholder="$t('请输入报价单')" disabled />
          </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">
          <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">
          <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">
          <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)" v-if="isEdit">{{$t('提交结果')}}</el-button>
    </div>
  </el-dialog>

  <customer-follow-select-offer  :customer-id="customerId" ref="customerFollowSelectOffer" @select="selectOffer" />

</div>
</template>

<script>
import {
  createCustomerFollow,
  getCustomerFollowPage,
  getCustomerFollowPage2,
  addCustomerFollow,
  getCustomerFollowList,
  editCustomerFollow
} from "@/api/ecw/customerFollow"
import { getOfferPage } from "@/api/ecw/offer"
import CustomerFollowSelectOffer from "./customerFollowSelectOffer";
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";
export default {
  /**
   * 客户跟进
   * 客户投诉跟进
   */
  name: "CustomerFollow",
  props: {
    /**
     * 如果是客户投诉跟进，则id为客户投诉id；如果是客户跟进，则id为客户id
     */
    id: Number,
    customerId: Number,
    customerQuery: {
      type: Boolean,
      default: false
    },
    customerNumber: String,
    customerService: Number
  },
  components: {
    FileUpload,
    CustomerFollowSelectOffer
  },
  data() {
    return {
      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()
        },
      },
      isEdit: true,
      followTime: [],
      nextTime: [],
      queryParams: {
        pageNo: 1,
        pageSize: 10
      },
      offerList: [],
      offerTotal: 0,
      isView: false
    }
  },
  computed: {
    isChinese() {
      return this.$i18n.locale === 'zh_CN'
    }
  },
  created() {
    this.init()
    // this.resetCustomerFollowForm()
    listServiceUser().then(r => {
      // console.log( r.data,'r.data跟进业务')
      this.serviceUserList = r.data
    })
    listAllSimpl().then((r) => {
      this.allSimplList = r.data;
    });
    // this.getCustomerFollowList()
    // this.reset()
  },
  methods: {
    init() {
      if (!!this.customerId) getCustomerContactsListByCustomer({
        customerId: this.customerId
      }).then(r => {
        this.customerContactsList = r.data
        // this.form.customerId = this.customerId
        // this.form.bizId = this.id
      })
    },
    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
      }
    },
    selectOffer(offerId) {
      this.form.offerId = offerId
    },
    reset() {
      this.form = {
        attatchment: undefined,
        contactId: undefined,
        contactName: undefined,
        contactPhone: undefined,
        customerId: this.customerId,
        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("不能小于当前时间"))
        }
      }
    },
    changeContactUser(val) {
      if (val) {
        for(const item of this.customerContactsList) {
          if (item.id == val) {
            this.form.contactName = item.name
            // this.form.contactPhone = `+${item.areaCode}${item.phoneNew}`
            break
          }
        }
      } else {
        this.form.contactName = null
        this.form.contactPhone = null
      }
    },
    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.resetCustomerFollowForm()
      this.customerFollow.dialogVisible = false
    },
    resetCustomerFollowForm() {
      this.reset()
      // this.$refs.dictType.changeValue(this.customerFollow.form.followType);
      this.$refs.dictMethod.changeValue(this.customerFollow.form.followMethod);
    },
    handleQuery() {
      this.pageNo = 1
      this.queryParams.pageNo = 1
      this.followTime = []
      this.getCustomerFollowList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        followType: null,
        followMethod: null,
        resultType: null,
        status: null
      };
      this.handleQuery();
    },
    getCustomerFollowList() {
      if (this.customerQuery) {
        getCustomerFollowList({
          customerId: this.customerId,
          pageNo: this.pageNo,
          pageSize: this.pageSize
        }).then(r => {
          this.$message.info(this.$t("操作成功"))
          this.$emit('refresh')
        })
      } else {
        getCustomerFollowPage2({
          bizId: this.id,
          followType: 3,
          pageNo: this.pageNo,
          pageSize: this.pageSize
        }).then(r => {
          this.$emit('refresh')
        })
      }
    },
    handleView(row) {
      this.isView = true
      this.form = row
      this.customerFollow.dialogVisible = true
    },
    handleAdd() {
      this.isView = false
      this.isEdit = true
      this.customerFollow.dialogVisible = true
      this.reset()
    },
    handleUpdate(row, flag) {
      this.isView = false
      this.isEdit = flag
      this.customerFollow.dialogVisible = true
      if (flag) {
        this.form = row
      } else {
        this.form = {
          ...row,
          parentNumber: row.number
        }
      }
    },
  }
}
</script>

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