<template>
  <el-dialog :title="title" :visible.sync="dialogFormVisible" @close="close">
    <el-form ref="form" label-width="96px" :model="form" :rules="rules">
      <el-row>
        <el-col :span="12">
          <el-form-item label="跟进时间" prop="followDate">
            <el-date-picker
              v-model="form.followDate"
              :picker-options="{
                // 时间不能大于当前时间
                disabledDate: (time) => {
                  return time.getTime() > Date.now()
                },
              }"
              placeholder="选择日期"
              style="width: 100%"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="跟进方式" prop="followType">
            <el-select v-model="form.followType" placeholder="请选择" style="width: 100%">
              <el-option v-for="item in followTypeOptions" :key="item.key" :label="item.value" :value="item.key" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="本次跟进内容" prop="followContent">
            <el-input
              v-model="form.followContent"
              placeholder="请输入本次跟进内容"
              rows="5"
              show-word-limit
              type="textarea" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="达成效果" prop="effect">
            <el-input v-model="form.effect" placeholder="请输入达成效果" rows="5" show-word-limit type="textarea" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="问题或困难" prop="issue">
            <el-input v-model="form.issue" placeholder="请输入问题或困难" rows="5" show-word-limit type="textarea" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="下一步跟进计划和目标" prop="furtherPlan">
            <el-input
              v-model="form.furtherPlan"
              placeholder="请输入下一步工作计划及完成时间"
              rows="5"
              show-word-limit
              type="textarea" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系人" prop="contactsName">
            <el-input v-model="form.contactsName" readonly suffix-icon="el-icon-search" @focus="handleSelectContact" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="上传附件" prop="files">
            <el-upload
              ref="uploadRef"
              action="#"
              :before-upload="
                (file) => {
                  return beforeAvatarUpload(file)
                }
              "
              :file-list="fileList"
              :http-request="uploadrequest">
              <el-button size="mini" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
        </el-col>
        <!--        <el-col :span="12">-->
        <!--          <el-form-item label="提醒对象" prop="reminders">-->
        <!--            <el-input v-model="form.reminders" />-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <!--        <el-col :span="12">-->
        <!--          <el-form-item label="下次联系时间" prop="nextTime">-->
        <!--            <el-date-picker v-model="form.nextTime" placeholder="选择日期" style="width: 100%" type="datetime" />-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <!--        <el-col :span="24">-->
        <!--          <el-form-item label="备注" prop="remark">-->
        <!--            <el-input v-model="form.remark" placeholder="请输入备注信息" rows="5" show-word-limit type="textarea" />-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button :loading="loading" type="primary" @click="save">确 定</el-button>
    </div>

    <!-- 选择客户联系人弹窗 -->
    <select-contact
      ref="selectContact"
      :default-customer="customerInfo"
      :query-params="queryContact"
      @save="selectContact" />

    <select-distributor
      ref="selectDistributor"
      :query-params="queryContact"
      :title="distrTitle"
      @save="selectContact" />
  </el-dialog>
</template>

<script>
  import axios from 'axios'
  import to from 'await-to-js'
  import followApi from '@/api/customer/follow'
  import SelectContact from '@/components/select/SelectCustomerContact'
  import SelectDistributor from '@/components/select/SelectDistributorContact'
  import asyncUploadFile from '@/utils/uploadajax'

  export default {
    name: 'FollowAdd',
    components: {
      SelectContact,
      SelectDistributor,
    },
    data() {
      return {
        distrTitle: '',
        loading: false,
        form: {
          followType: '',
          followDate: '',
          followContentType: '',
          effect: '',
          followContent: '',
          issue: '',
          furtherPlan: '',
          targetId: '',
          targetName: '',
          targetType: '',
          custId: 0,
          custName: '',
          contactsId: '',
          contactsName: '',
          reminders: '',
          nextTime: '',
          remark: '',
          supportName: '',
          files: [],
        },
        rules: {
          followType: [{ required: true, trigger: 'blur', message: '请输入跟进方式' }],
          followDate: [{ required: true, trigger: 'blur', message: '请输入跟进时间' }],
          followContentType: [{ required: true, trigger: 'blur', message: '请输入跟进内容类型' }],
          followContent: [{ required: true, trigger: 'blur', message: '请输入本次跟进内容' }],
          effect: [{ required: true, trigger: 'blur', message: '请输入达成效果' }],
          issue: [{ required: true, trigger: 'blur', message: '请输入问题或困难' }],
          furtherPlan: [{ required: true, trigger: 'blur', message: '请输入下一步跟进计划和目标' }],
          targetId: [{ required: true, trigger: 'blur', message: '请选择跟进对象' }],
          targetName: [{ required: true, trigger: 'blur', message: '跟进对象不能为空' }],
          targetType: [{ required: true, trigger: 'blur', message: '跟进对象类型不能为空' }],
          custId: [{ required: true, trigger: 'blur', message: '请选择关联客户' }],
          custName: [{ required: true, trigger: 'blur', message: '客户名称不能为空' }],
          contactsId: [{ required: true, trigger: 'blur', message: '请选择关联联系人' }],
          contactsName: [{ required: true, trigger: 'blur', message: '联系人姓名不能为空' }],
          supportName: [{ required: true, trigger: 'blur', message: '总部支持人员不能为空' }],
        },
        title: '',
        dialogFormVisible: false,
        fileList: [],
        fileSettings: {
          // 文件配置信息
          fileSize: 52428800,
          fileTypes: '.doc,.docx,.zip,.xls,.xlsx,.rar,.jpg,.jpeg,.gif,.png,.jfif,.txt',
          pictureSize: 52428800,
          pictureTypes: '.jpg,.jpeg,.gif,.png,.jfif,.txt',
          types: '.doc,.docx,.zip,.xls,.xlsx,.rar,.jpg,.jpeg,.gif,.png,.jfif,.mp4,.txt',
          videoSize: 104857600,
          videoType: '.mp4',
        },
        queryContact: {},
        customerInfo: {},
        followTypeOptions: [],
        followContentTypeOptions: [],
      }
    },
    watch: {},
    created() {
      this.getOptions()
    },
    methods: {
      getOptions() {
        Promise.all([this.getDicts('plat_follow_type'), this.getDicts('plat_follow_content_type')]).then(
          ([followType, followContentType]) => {
            this.followTypeOptions = followType.data.values || []
            this.followContentTypeOptions = followContentType.data.values || []
          }
        )
      },
      handleSelectContact() {
        console.log(this.form.targetType)
        if (this.form.targetType == '50') {
          this.$refs.selectDistributor.open()
        } else {
          if (!this.queryContact.custId) {
            this.$message.warning('请先选择客户')
            return
          }
          this.$refs.selectContact.open()
        }
      },
      selectContact(val) {
        if (val && val.length > 0) {
          if (this.form.targetType == '50') {
            this.form.contactsName = val.map((item) => item.name).join()
          } else {
            this.form.contactsName = val.map((item) => item.cuctName).join()
          }
          this.form.contactsId = val[0].id
        }
        console.log(this.form)
      },
      showEdit(row, title = null) {
        this.title = '添加跟进记录'
        this.form = Object.assign(this.form, row)
        console.log(this.form)
        if (this.form.targetType == '10' || this.form.targetType == '20' || this.form.targetType == '60') {
          this.queryContact.custId = this.form.custId
          this.customerInfo = {
            custId: this.form.custId,
            custName: this.form.custName,
          }
        } else if (this.form.targetType == '50') {
          this.queryContact.distId = this.form.targetId
        }
        this.distrTitle = title
        this.dialogFormVisible = true
      },
      close() {
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
        this.fileList = []
        this.dialogFormVisible = false
        this.loading = false
      },
      save() {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            this.loading = true
            const [err, res] = await to(followApi.addFollowUp(this.form))
            if (err) {
              this.$baseMessage(res.msg, 'error')
            } else {
              this.$baseMessage(res.msg, 'success')
            }
            this.loading = false
            this.$emit('fetch-data')
            this.close()
          } else {
            return false
          }
        })
      },

      // 上传图片
      beforeAvatarUpload(file) {
        let flag1 = file.size < this.fileSettings.fileSize
        if (!flag1) {
          this.$message.warning('文件过大，请重新选择！')
          return false
        }
        let flag2 = this.fileSettings.fileTypes.split(',').includes('.' + file.name.split('.').pop())
        if (!flag2) {
          this.$message.warning('文件类型不符合，请重新选择！')
          return false
        }
        return true
      },
      // 上传
      uploadrequest(option) {
        let _this = this
        let url = process.env.VUE_APP_UPLOAD_WEED
        axios
          .post(url)
          .then(function (res) {
            if (res.data && res.data.fid && res.data.fid !== '') {
              option.action = `${process.env.VUE_APP_PROTOCOL}${res.data.publicUrl}/${res.data.fid}`
              let file_name = option.file.name
              let index = file_name.lastIndexOf('.')
              let file_extend = ''
              if (index > 0) {
                // 截取名称中的扩展名
                file_extend = file_name.substr(index + 1)
              }
              let uploadform = {
                fileName: file_name, // 资料名称
                fileUrl: `${process.env.VUE_APP_PROTOCOL}${res.data.publicUrl}/${res.data.fid}`, // 资料存储url
                size: option.file.size.toString(), // 资料大小
                fileType: file_extend, // 资料文件类型
              }
              asyncUploadFile(option).then(() => {
                _this.form.files.push(uploadform)
              })
            } else {
              _this.$message({
                type: 'warning',
                message: '未上传成功！请刷新界面重新上传！',
              })
            }
          })
          .catch(function () {
            _this.$message({
              type: 'warning',
              message: '未上传成功！请重新上传！',
            })
          })
      },
    },
  }
</script>
