<template>
  <!-- 成交登记对话框 -->
  <el-dialog title="成交登记" :visible.sync="visible" width="800px" append-to-body :close-on-click-modal="false" v-loading="signLoading" style>
    <!-- <div style="height:500px;overflow-y:auto;"> -->
    <span style="color:red;">输入联系方式后会进行线索数据匹配！</span>
    <el-form :model="modalForm" ref="modalForm" :rules="modalRules" label-width="110px" :disabled="!modalForm.signEdit">
      <el-row>
        <el-col :span="12">
          <el-form-item label="学员联系方式" prop="phone">
            <el-input v-model="modalForm.phone" :disabled="modalForm.clueId != undefined || !modalForm.phoneEdit" @blur="searchClue"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="学员姓名" prop="name">
            <el-input v-model="modalForm.name" :disabled=" modalForm.clueId != undefined"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="线索来源" prop="source">
            <el-select v-model="modalForm.source" placeholder="请选择" clearable size="small" :disabled="modalForm.clueId != undefined">
              <el-option v-for="(dict, index) in sourceOptions" :key="index" :label="dict.dictLabel" :value="dict.dictValue" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否全款" prop="state">
            <el-radio-group v-model="modalForm.state">
              <el-radio :label="true">全款</el-radio>
              <el-radio :label="false">非全款</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="成交日期" prop="dealDate">
            <el-date-picker v-model="modalForm.dealDate" size="small" :picker-options="dateControl" value-format="yyyy-MM-dd" format="yyyy-MM-dd" type="date"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="报名价格(元)" prop="signPrice">
            <el-input v-model="modalForm.signPrice" placeholder="学员报名时需要交纳总共的钱" @blur="priceChange"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="报名驾校" prop="signSchool">
            <el-select v-model="modalForm.signSchool" filterable placeholder="请选择" value-key="schoolId" clearable size="small" @change="schoolChange">
              <el-option v-for="(dict, index) in schoolOptions" :key="index" :label="dict.schoolName" :value="dict.schoolId" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="报名场地" prop="signPlace">
            <el-select v-model="modalForm.signPlace" filterable placeholder="请选择" clearable value-key="placeId" size="small" @change="placeChange">
              <el-option v-for="(dict, index) in placeOptions" :key="index" :label="dict.name" :value="dict.placeId" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="报名班型" prop="signClass">
            <el-select v-model="modalForm.signClass" filterable placeholder="请选择" clearable value-key="typeId" size="small" @change="priceChange">
              <el-option v-for="(dict, index) in classTypeOptions" :key="index" :label="`${dict.licenseType}-${dict.typeName}`" :value="dict.typeId" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="对接人" prop="schoolPeople">
            <el-input v-model="modalForm.schoolPeople"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="驾校支付" prop="schoolPay">
            <el-input type="number" v-model="modalForm.schoolPay" placeholder="请输入驾校支付金额" disabled></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="驾考宝典款" prop="alipay">
            <el-input v-model="modalForm.alipay" placeholder="请输入驾考宝典款金额"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="额外支出" prop="extraPayType">
            <el-select v-model="modalForm.extraPayTypes" filterable multiple placeholder="请选择" clearable size="small">
              <el-option v-for="(dict, index) in extraPayTypeOptions" :key="index" :label="dict.dictLabel" :value="dict.dictValue" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="额外支出金额" prop="extraPay">
            <el-input placeholder="请输入额外支出金额" v-model="modalForm.extraPay"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="归属人员" prop="followUser">
            <el-select v-model="modalForm.followUser" multiple placeholder="请选择" clearable size="small" :disabled="modalForm.clueId != undefined">
              <el-option v-for="(dict, index) in userOptions" :key="index" :label="dict.name" :value="dict.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属区域" prop="area">
            <el-select v-model="modalForm.area" placeholder="请选择" clearable size="small">
              <el-option v-for="(dict, index) in areaOptions" :key="index" :label="dict.dictLabel" :value="dict.dictValue" />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
              <el-form-item label="线下接待人员" prop="offlineReceiver">
                <el-select v-model="modalForm.offlineReceiver" multiple placeholder="请选择" clearable size="small" :disabled="modalForm.clueId != undefined">
                  <el-option v-for="dict in userOptions" :key="dict.id" :label="dict.name" :value="dict.id" />
                </el-select>
              </el-form-item>
          </el-col>-->
      </el-row>

      <el-row v-if="admin == 'true'">
        <el-col :span="12">
          <el-form-item label="佣金明细" prop="commission">
            <el-select v-model="modalForm.commission" placeholder="请选择" clearable size="small">
              <el-option v-for="(dict, index) in commissionOptions" :key="index" :label="dict.dictLabel" :value="dict.dictValue" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="memo">
            <el-input type="textarea" :rows="2" v-model="modalForm.memo"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-form-item label="凭据" prop="evidence">
          <el-upload ref="signUpload" accept="image/*" list-type="picture-card" :file-list="fileList" :headers="signUpload.headers" :action="signUpload.url + '?type=2'" class="evidence-uploader" multiple :disabled="!modalForm.signEdit" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
            <i class="el-icon-plus evidence-uploader-icon" />
          </el-upload>

          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>

          <!-- <div class="demo-image__preview">
            <div v-for="(item, index) in fileList" :key="index" class="demo-image__item">
              <el-image class="image-list-item" fit="contain" :src="preUrl + item.url" :preview-src-list="fileList.map(file => preUrl + file.url)" lazy>
                <i class="el-icon-close btn-close" @click="handleRemoveImage(index,item)" v-show="modalForm.signEdit" />

              </el-image>
            </div>
          </div> -->
        </el-form-item>
      </el-row>

      <el-row v-if="modalForm  && modalForm.signId">
        <el-col :span="24">
          <el-form-item label="审核记录">
            <CheckRecord :signId="modalForm.signId" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- </div> -->
    <span slot="footer" v-if="modalForm.signEdit">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" :disabled="!canSubmit" @click="handleSubmit">提 交</el-button>
    </span>
  </el-dialog>
</template>
  
  <script>
import { addSign, updateSign } from '@/api/zs/sign'
import { validateMoney } from '@/utils/validate'
import { getToken } from '@/utils/auth'
import empApi from '@/api/system/employee'
import schoolAPi from '@/api/sch/school'
import { getAllPlaces } from '@/api/sch/place'
import { getClassTypeTableList } from '@/api/sch/classType'
import { uploadEvidence, deleteFile, } from '@/api/tool/common'
import { getClueList } from '@/api/zs/clue'

import CheckRecord from './CheckRecord.vue'

export default {
  name: 'SignFormDialog',
  components: {
    CheckRecord
  },
  props: {
    clueInfo: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      admin: localStorage.getItem('admin'),
      preUrl: process.env.VUE_APP_BASE_API,
      userId: localStorage.getItem('userId'),
      loading: {
        tableLoading: false,
        modalSaveLoading: false,
      },
      visible: false,
      signLoading: false,
      modalForm: {},
      modalRules: {
        name: { required: true, message: '姓名不为空', trigger: 'blur' },
        phone: { required: true, message: '联系方式不为空', trigger: 'blur' },
        source: { required: true, message: '线索来源不为空', trigger: 'blur' },
        area: { required: true, message: '所属区域不为空', trigger: 'blur' },
        dealDate: { required: true, message: '成交时间不为空', trigger: 'blur,change', },
        state: { required: true, message: '是否权限必选', trigger: 'blur,change', },
        followUser: { required: true, message: '归属人员不为空', trigger: 'blur,change', },
        signSchool: { required: true, message: '报名驾校不为空', trigger: 'blur,change', },
        signPlace: { required: true, message: '报名场地不为空', trigger: 'blur,change', },
        signClass: { required: true, message: '报名班型不为空', trigger: 'blur,change', },
        dealState: { required: true, message: '结算情况不为空', trigger: 'blur,change', },
        signPrice: { required: true, validator: validateMoney, trigger: 'blur', },
      },
      userOptions: [],
      clueOptions: [],
      schoolOptions: [],
      placeOptions: [],
      classTypeOptions: [],
      sourceOptions: [],
      commissionOptions: [],
      extraPayTypeOptions: [],
      percentageOptions: [
        {
          value: '驾校已结算',
          label: '驾校已结算',
        },
        {
          value: '提成已发放',
          label: '提成已发放',
        },
      ],
      dateControl: undefined,
      areaOptions: [],
      fileList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      uploadFile: undefined,
      checkRecord: [],
      canSubmit: true,
      signUpload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/common/upload',
      }
    }
  },
  created() {

    //线索来源
    this.getDicts('dm_source').then((response) => {
      this.sourceOptions = response.data
    })
    //意向状态
    this.getDicts('dm_intention_state').then((response) => {
      this.intentionOptions = response.data
    })
    //佣金明细
    this.getDicts('dm_commission').then((response) => {
      this.commissionOptions = response.data
    })
    //额外支出类型
    this.getDicts('dm_extra_pay').then((response) => {
      this.extraPayTypeOptions = response.data
    })
    //所属区域
    this.getDicts('dm_area').then((response) => {
      this.areaOptions = response.data
    })
    this.getSchools()
    this.getEmployee()

  },
  methods: {
    init(info = undefined) {
      this.fileList = []
      this.picList = []
      this.canSubmit = true;
      this.checkRecord = []
      this.$nextTick(() => {
        this.resetForm('modalForm')
        this.resetForm();
        //如果是线索页面的弹框，则处理
        this.dealClue(this.clueInfo);
        if (info && info.signId) {
          //修改
          this.handleUpdate(info)
        } else {
          //新增
          this.handleAdd()
        }
        this.visible = true;
      });
    },
    getSchools() {
      schoolAPi.pageList().then((resp) => {
        this.schoolOptions = resp.rows
      })
    },
    getPlaces(schoolId) {
      getAllPlaces({ schoolId: schoolId, status: '0' }).then((resp) => {
        this.placeOptions = resp.data
      })
    },
    getClassTypes(schoolId, placeId) {
      getClassTypeTableList({ schoolId: schoolId, placeId: placeId, status: '0' }).then(
        (resp) => {
          this.classTypeOptions = resp.rows
        }
      )
    },
    getEmployee() {
      empApi.getEmployee().then((resp) => {
        if (resp.code == 200) {
          this.userOptions = resp.data
        }
      })
    },
    checkDate(date) {
      let dealDate = new Date(date)
      let year = dealDate.getFullYear() //得到年份
      let month = dealDate.getMonth() + 1 //得到月份
      let endDate = new Date(year, month, 5)
      let now = new Date()
      if (now.getTime() >= endDate.getTime()) {
        this.signEdit = true
      }
    },
    //驾校change事件
    schoolChange(e) {
      this.$set(this.modalForm, 'signPlace', undefined)
      this.$set(this.modalForm, 'signClass', undefined)
      this.classTypeOptions = []
      this.$set(this.modalForm, 'schoolPeople', undefined)
      this.$set(this.modalForm, 'area', undefined)
      this.getPlaces(e)
    },
    //場地change事件
    placeChange() {
      this.$set(this.modalForm, 'signClass', undefined)
      if (this.modalForm.signPlace) {
        const place = this.placeOptions.find(
          (item) => item.placeId === this.modalForm.signPlace
        )
        this.$set(this.modalForm, 'schoolPeople', place.contact)
        this.$set(this.modalForm, 'area', place.area)
        this.getClassTypes(this.modalForm.signSchool, this.modalForm.signPlace)
      } else {
        this.classTypeOptions = []
        this.$set(this.modalForm, 'schoolPeople', undefined)
        this.$set(this.modalForm, 'area', undefined)
      }
    },
    handleAdd() {
      this.placeOptions = []
      this.classTypeOptions = []
      this.setDate(true)
    },
    handleUpdate(item) {
      this.setDate(false)
      this.modalForm = Object.assign({}, item)
      this.getPlaces(this.modalForm.signSchool)
      this.getClassTypes(this.modalForm.signSchool, this.modalForm.signPlace)
      this.modalForm.phoneEdit = false
      if (this.modalForm.fileList) {
        this.fileList = this.modalForm.fileList
      }
    },
    //重置表单
    resetForm() {
      let now = new Date()
      let year = now.getFullYear() //得到年份
      let month = now.getMonth() + 1 //得到月份
      let date = now.getDate() //得到日期
      this.modalForm = {
        signId: undefined,
        clueId: undefined,
        name: undefined,
        phone: undefined,
        source: undefined,
        followUser: [this.userId],
        offlineReceiver: undefined,
        dealDate: year + '-' + month + '-' + date,
        signSchool: undefined,
        signPlace: undefined,
        signClass: undefined,
        signPrice: undefined,
        schoolPeople: undefined,
        schoolPay: undefined,
        alipay: undefined,
        profit: undefined,
        percentage: undefined,
        detail: undefined,
        dealState: undefined,
        extraPayType: undefined,
        extraPayTypes: undefined,
        extraPay: undefined,
        percentageState: undefined,
        memo: undefined,
        createTime: undefined,
        updateTime: undefined,
        state: true,
        commission: undefined,
        signEdit: true,
        phoneEdit: true,
        fileList: []
      }
    },
    setDate(flag) {
      let now = new Date()
      let year = now.getFullYear() //得到年份
      let month = now.getMonth() //得到月份
      let start = new Date(year, month - 1, 1)
      //   console.log(new Date(year, month , 9, 9))
      if (flag && now >= new Date(year, month, 5)) {
        start = new Date(year, month, 1)
      }
      if (this.admin != 'true') {
        this.dateControl = {
          disabledDate: (time) => {
            return time.getTime() < start || time.getTime() >= new Date()
          },
        }
      }
    },
    handleSignSave() {
      this.modalForm.checkState = 1
      this.modalForm.fileList = this.fileList
      //保存登记表
      this.$refs.modalForm.validate((valid) => {
        if (valid) {
          this.canSubmit = false;
          if (this.modalForm.signId) {
            updateSign(this.modalForm).then((resp) => {
              if (resp.code == 200) {
                this.$message.success('提交成功')
                this.visible = false
                this.$emit('refreshDataList');
              } else {
                this.canSubmit = true;
              }
            })
          } else {
            addSign(this.modalForm).then((resp) => {
              if (resp.code == 200) {
                this.$message.success('提交成功')
                this.visible = false
                this.$emit('refreshDataList')
              } else {
                // this.$message.error("登记失败:" + resp.msg);
                this.canSubmit = true;
              }
            })
          }
        }
      })
    },
    handleSubmit() {
      this.$confirm('提交后将进入审核阶段，是否提交确认提交?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then((res) => {
          this.handleSignSave()
        })
        .catch(function () { })
    },
    //自动检索对应的线索
    searchClue(e) {
      console.log(e.target.value)
      if (e.target.value && e.target.value != '') {
        this.signLoading = true
        getClueList({ state: false, name: e.target.value }).then((response) => {
          if (response.code == 200 && response.rows && response.rows[0]) {
            this.dealClue(response.rows[0]);
          } else {
            this.dealClue(undefined);
          }
          this.signLoading = false
        })
      } else {
        this.dealClue(undefined);
      }
    },
    //检索到的线索进行赋值
    dealClue(clueInfo) {
      if (clueInfo) {
        this.modalForm.clueId = clueInfo.clueId
        this.modalForm.name = clueInfo.name
        this.modalForm.phone = clueInfo.phone
        this.modalForm.source = clueInfo.source
        this.modalForm.followUser = clueInfo.followUser
        this.modalForm.offlineReceiver = clueInfo.offlineReceiver
      } else {
        this.modalForm.clueId = undefined
        this.modalForm.name = undefined
        this.modalForm.source = undefined
        this.modalForm.followUser = undefined
        this.modalForm.offlineReceiver = undefined
      }
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
      this.fileList = fileList
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // handleSuccess(response, file, fileList) {
    //   console.log(file, fileList)
    // },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      console.log(file, fileList)
      this.signUpload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      console.log(file, fileList)
      this.signUpload.isUploading = false;
      this.$refs.signUpload.clearFiles();
      // this.dialogImageUrl = process.env.VUE_APP_BASE_API + response.fileName
      this.fileList.push({ name: response.newFileName, url: process.env.VUE_APP_BASE_API + response.fileName })
    },
    handleUploadFile(param) {
      let fileObj = param.file

      const isLt2M = fileObj.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return
      }
      if (fileObj.type === 'image/jpeg') {
        this.uploadFile = new File([fileObj], new Date().getTime() + '.jpg', {
          type: 'image/jpeg',
        })
        this.upload()
      } else if (fileObj.type === 'image/png') {
        this.uploadFile = new File([fileObj], new Date().getTime() + '.png', {
          type: 'image/png',
        })
        this.upload()
      } else {
        this.$message.error('只能上传jpg/png文件')
        return
      }
    },
    upload() {
      var param = new FormData() // FormData 对象
      param.append('file', this.uploadFile) // 文件对象
      param.append('name', 'ziguiyu') // 其他参数
      uploadEvidence(param)
        .then((response) => {
          if (response.code == 200) {
            // this.$message({
            //   message: '上传成功',
            //   type: 'success'
            // });
            //this.form.logo = "https://duima.cainiao-xueche.com:8443/duima" + response.data;
            this.dialogImageUrl = process.env.VUE_APP_BASE_API + response.data
            this.fileList.push({ name: '', url: this.dialogImageUrl })
            // this.dialogImageUrl = file.url;
            // this.dialogVisible = true;
          }
        })
        .catch((error) => {
          this.$message.error('上传失败,请稍后重试')
        })
    },
    handleRemoveImage(index, item) {
      deleteFile(item).then((resp) => {
        if (resp && resp.data)
          // 最好先通过接口删除服务器图片
          this.modalForm.fileList.splice(index, 1)
      })
    },
    priceChange() {
      //计算驾校支付款  报名价格-班型底价
      if (this.modalForm.signClass && this.modalForm.signPrice) {
        const minprice = this.classTypeOptions.find(
          (item) => item.typeId == this.modalForm.signClass
        ).minPrice
        if (minprice) {
          this.$set(this.modalForm, 'schoolPay', this.modalForm.signPrice - minprice)
        }
      } else {
        this.$set(this.modalForm, 'schoolPay', undefined)
      }
    },
  },
}
  </script>

  <style scoped>
.demo-image__item {
  width: 100px;
  height: 100px;
  display: inline-block;
}
.image-list-item {
  width: 100%;
  height: 100%;
}
.el-upload--picture-card {
  width: 100px !important;
  height: 100px !important;
}
</style>
  
  