<template>
  <el-form ref="form" :model="form" :rules="rules" label-width="110px" :disabled="form.signId != undefined && !form.signEdit">
    <el-row>
      <el-col :span="12">
        <el-form-item label="学员姓名">
          <el-input v-model="form.name" disabled />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="学员联系方式">
          <el-input v-model="form.phone" disabled />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="线索来源">
          <el-select v-model="form.source" disabled>
            <el-option v-for="dict in options.sourceOptions" :key="dict.dictValue" :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="form.state">
            <el-radio :label="true">全款</el-radio>
            <el-radio :label="false">非全款</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="成交日期" prop="dealDate">
          <el-date-picker v-model="form.dealDate" :picker-options="dateControl" value-format="yyyy-MM-dd" format="yyyy-MM-dd" type="date" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="报名价格(元)" prop="signPrice">
          <el-input v-model="form.signPrice" placeholder="学员报名时需要交纳总共的钱" @blur="priceChange" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="报名驾校" prop="signSchool">
          <el-select v-model="form.signSchool" filterable placeholder="请选择" @change="schoolChange">
            <el-option v-for="dict in schoolOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="报名场地" prop="signPlace">
          <el-select v-model="form.signPlace" filterable placeholder="请选择" @change="placeChange">
            <el-option
              v-for="dict in options.placeInfo.filter((item) => item.deptId === form.signSchool)"
              :key="dict.placeId"
              :label="dict.name"
              :value="dict.placeId"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="报名班型" prop="signClass">
          <el-select v-model="form.signClass" filterable placeholder="请选择" @change="priceChange">
            <el-option
              v-for="dict in classTypeOptions.filter((item) => (!item.placeId && item.deptId === form.signSchool) || item.placeId === form.signPlace)"
              :key="dict.typeId"
              :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="form.schoolPeople" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="驾校支付" prop="schoolPay">
          <el-input v-model="form.schoolPay" type="number" placeholder="请输入驾校支付金额" disabled />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="驾考宝典款" prop="alipay">
          <el-input v-model="form.alipay" placeholder="请输入驾考宝典款金额" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="额外支出" prop="extraPayType">
          <el-select v-model="form.extraPayTypes" filterable placeholder="请选择" multiple clearable>
            <el-option v-for="dict in extraPayTypeOptions" :key="dict.dictValue" :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 v-model="form.extraPay" placeholder="请输入额外支出金额" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="归属人员" prop="followUser">
          <el-select v-model="form.followUser" multiple placeholder="请选择" clearable :disabled="true">
            <el-option v-for="dict in options.userOptions" :key="dict.id" :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="form.area" placeholder="请选择" clearable>
            <el-option v-for="dict in areaOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col v-if="admin" :span="12">
        <el-form-item label="佣金明细" prop="commission">
          <el-select v-model="form.commission" placeholder="请选择" clearable>
            <el-option v-for="dict in commissionOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="备注" prop="memo">
          <el-input v-model="form.memo" type="textarea" :rows="2" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-form-item label="凭据" prop="evidence">
        <el-upload action="#" class="evidence-uploader" :http-request="handleUploadFile" accept="image/*" :show-file-list="false" multiple>
          <i class="el-icon-plus evidence-uploader-icon" />
        </el-upload>
        <div v-for="(item, index) in form.fileList" :key="index" class="pr dib">
          <el-image class="image-list-item" fit="contain" :src="preUrl + item" :preview-src-list="form.fileList.map((url) => preUrl + url)" lazy />
          <i class="el-icon-close btn-close" @click="handleRemoveImage(index, item)" />
        </div>
      </el-form-item>
    </el-row>

    <el-row v-if="checkRecord && checkRecord.length > 0">
      <el-col :span="24">
        <el-form-item label="审核记录">
          <el-timeline style="max-height: 260px; overflow-y: auto">
            <el-timeline-item
              v-for="item in checkRecord"
              :key="item.record"
              :timestamp="item.operateTime"
              placement="top"
              style="padding: 5px !important"
            >
              <el-card>
                <span style="display: block; font-weight: bold; font-size: 13px">用户 {{ item.operateUserName }}</span>
                <span style="display: block; padding-left: 10px; font-size: 13px" v-html="item.centent" />
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script>
import { validateMoney } from '@/utils/validate';
import { getSchools, getClassTypeInfo, uploadEvidence, deleteFile } from '@/api/tool/common';
import { getCheckRecord } from '@/api/zs/sign';
export default {
  name: 'SignForm',
  model: {
    prop: 'info',
    event: 'update'
  },
  props: {
    info: {
      type: Object,
      default: () => {}
    },
    options: {
      type: Object,
      default: () => ({
        userOptions: [],
        sourceOptions: [],
        placeInfo: []
      })
    }
  },
  data() {
    return {
      admin: JSON.parse(localStorage.getItem('admin')),
      preUrl: process.env.VUE_APP_BASE_API,
      form: JSON.parse(JSON.stringify(this.info)),
      rules: {
        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'
        }
      },
      schoolOptions: [],
      placeOptions: [],
      classTypeOptions: [],
      areaOptions: [],
      commissionOptions: [],
      extraPayTypeOptions: [],
      dateControl: undefined,
      checkRecord: []
    };
  },
  watch: {
    form: {
      handler(val) {
        this.$emit('update', val);
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    if (!this.form.fileList) {
      this.$set(this.form, 'fileList', []);
    }
    this.initData();
  },
  methods: {
    initData() {
      // 佣金明细
      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;
      });
      // 驾校
      getSchools().then((resp) => {
        this.schoolOptions = resp.data;
      });
      // 班型
      getClassTypeInfo({ status: '0' }).then((resp) => {
        this.classTypeOptions = resp.data;
      });
      // 审核记录
      this.form.signId &&
        getCheckRecord({
          signId: this.form.signId,
          type: 1
        }).then((resp) => {
          this.checkRecord = resp.data;
        });
      // 未登记并且非管理员，添加日期规则
      if (!this.form.signId) {
        let start = new Date();
        // 取1号
        start.setDate(1);
        // 5号之前可操作上个月，注意跨年
        if (new Date().getDate() < 5) {
          if (start.getMonth() > 0) {
            start.setMonth(start.getMonth() - 1);
          } else {
            start.setFullYear(start.getFullYear() - 1);
            start.setMonth(11);
          }
        }
        // 因为new Date()出来的时间戳，包含时分秒，判断日期时需要减一天
        start = start.getTime() - 24 * 60 * 60 * 1000;
        this.dateControl = {
          disabledDate: (time) => {
            return time.getTime() < start || time.getTime() > new Date();
          }
        };
      }
    },
    validate() {
      return this.$refs.form.validate();
    },
    // 驾校change事件
    schoolChange() {
      this.$set(this.form, 'signPlace', undefined);
      this.$set(this.form, 'signClass', undefined);
    },
    placeChange() {
      this.$set(this.form, 'signClass', undefined);
      this.$set(this.form, 'schoolPeople', this.options.placeInfo.find((item) => item.placeId === this.form.signPlace).contact);
      this.$set(this.form, 'area', this.options.placeInfo.find((item) => item.placeId === this.form.signPlace).area);
      // this.form.schoolPeople = this.options.placeInfo.find(
      //   (item) => item.placeId === this.form.signPlace
      // ).contact
    },
    async handleUploadFile(data) {
      if (data.file) {
        const size = data.file.size;
        const limitSize = 20 * 1024 * 1024; // 20M大小限制
        if (size < limitSize) {
          const formData = new FormData();
          formData.append('file', data.file);
          const resp = await uploadEvidence(formData);
          if (resp.code === 200) {
            this.form.fileList.push(resp.data);
          }
        } else {
          this.msgInfo('文件过大');
        }
      }
    },
    handleRemoveImage(index, item) {
      deleteFile(item).then((resp) => {
        if (resp && resp.data) {
          // 最好先通过接口删除服务器图片
          this.form.fileList.splice(index, 1);
        }
      });
    },
    priceChange() {
      // 计算驾校支付款  报名价格-班型底价
      if (this.form.signClass && this.form.signPrice) {
        let minprice;
        this.classTypeOptions.some((item) => {
          if (item.typeId == this.form.signClass) {
            minprice = item.minPrice;
            return item;
          }
        });
        if (minprice) {
          this.$set(this.form, 'schoolPay', this.form.signPrice - minprice);
        }
      } else {
        this.$set(this.form, 'schoolPay', undefined);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.el-row {
  display: flex;
  flex-wrap: wrap;
}
.evidence-uploader {
  display: inline-block;
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;

    &:hover {
      border-color: #409eff;
    }
    .evidence-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      line-height: 100px;
      text-align: center;
    }
  }
}
.image-list-item {
  height: 100px;
  img {
    width: auto;
  }
}

.btn-close {
  position: absolute;
  right: 0;
  top: 0;
  padding: 2px;
  font-size: 20px;
  background: #f2f6fc;
}
</style>
