<template>
  <basic-container v-loading="loadingObj.pageLoading">
    <div class="avue-crud">
      <el-form label-width="140px" ref="formRef" :inline="true" :model="form">
        <el-form-item
          style="width: 30%"
          :label="item.label"
          v-for="item in option"
          :key="item.prop"
          :prop="item.prop"
          :rules="item.rules"
        >
          <!-- 输入框 -->
          <el-input
            clearable
            v-model="form[item.prop]"
            @input="() => item.input && item.input(form[item.prop], item)"
            v-if="item.type == 'input'"
            :placeholder="item.placeholder || '请输入' + item.label"
          />

          <!-- 数字输入框 -->
          <el-input-number
            v-model="form[item.prop]"
            @input="() => item.input && item.input(form[item.prop], item)"
            clearable
            v-else-if="item.type == 'number'"
            :precision="item.precision"
            :min="item.min || 0"
            :controls="false"
            :placeholder="item.placeholder || '请输入' + item.label"
            class="w100"
            :value-on-clear="item.min || 0"
          />

          <!-- 日期 -->
          <el-date-picker
            v-model="form[item.prop]"
            v-else-if="item.type == 'date'"
            clearable
            type="date"
            :placeholder="item.placeholder || '请选择' + item.label"
            :disabled-date="disabledDate"
            class="w100"
            :value-format="item.valueFormat || 'yyyy-MM-dd'"
          />

          <!-- 下拉框 -->
          <el-select
            v-else-if="item.type == 'select'"
            v-model="form[item.prop]"
            class="w100"
            clearable
            :placeholder="item.placeholder || '请选择' + item.label"
            :multiple="item.multiple || false"
            :filterable="item.filterable || false"
          >
            <el-option
              v-for="value in item.options"
              :key="value.dictKey"
              :label="value.dictValue"
              :value="value.dictKey"
            />
          </el-select>
        </el-form-item>

        <div class="img-container">
          <el-form-item
            style="width: 30%"
            :label="item.label"
            v-for="item in imgOption"
            :key="item.prop"
            :prop="item.prop"
            :rules="item.rules"
          >
            <el-upload
              list-type="picture-card"
              :show-file-list="false"
              :on-preview="handlePreview"
              :action="'/api/blade-resource/oss/endpoint/put-file'"
              :on-success="file => handleUpLoadSuccess(file, item)"
              :before-upload="handleBeforeUpload"
              :on-exceed="() => handleImgError(item)"
              :headers="headers"
            >
              <div v-if="form[item.prop]" @click.stop class="upLoadImg_box">
                <el-image
                  :src="form[item.prop]"
                  class="avatar"
                  :preview-src-list="[form[item.prop]]"
                />

                <div class="clearIcon" @click="() => handleRemoveImg(item)">
                  <el-icon color="#f00"><DeleteFilled /></el-icon>
                </div>
              </div>
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="submit_container">
      <el-button icon="CircleClose" @click="back">关 闭</el-button>
      <el-button icon="Refresh" type="primary" @click="handleReset">重 置</el-button>
      <el-button icon="Promotion" type="primary" @click="submitForm">保 存</el-button>
    </div>
  </basic-container>
</template>

<script>
import {
  getList,
  getDetail,
  add,
  update,
  remove,
  getPage,
} from '@/api/basicdata/basicdataDriverArtery';
/** 获取字典 */
import { getDictionaryBiz } from '@/api/system/dict';
import { getVehicle, getListName, getDictionary } from '@/api/basicdata/basicdataVehicle';
import { mapGetters } from 'vuex';
import { getToken } from '@/utils/auth';
import { downloadXls, setNodeHeight, debounce } from '@/utils/util';
import { ElMessageBox } from 'element-plus';
export default {
  name: '/basicdata/driverArtery/basicdataDriverArteryAdd',
  data() {
    return {
      // 表单数据
      form: {},
      option: [
        {
          label: '姓名',
          prop: 'name',
          type: 'input',
          rules: [{ required: true, message: '请输入姓名!', trigger: ['blur', 'change'] }],
        },
        {
          label: '手机号码',
          prop: 'phone',
          type: 'input',
          precision: 0,
          blur(payload) {
            console.log('payload :>> ', payload);
            payload.value = payload.value + 1;
            console.log('111 :>> ', 111);
          },

          rules: [
            {
              required: true,
              message: '请输入电话号码',
              trigger: 'blur',
            },
          ],
        },
        {
          label: '司机类型',
          prop: 'type',
          filterable: true,
          type: 'select',
          dicUrl: '/api/blade-system/dict-biz/dictionary?code=basic_driver_type',
          options: [],
        },
        {
          label: '职务类型',
          prop: 'jobType',
          filterable: true,
          type: 'select',
          dicUrl: '/api/blade-system/dict-biz/dictionary?code=basic_driverjob_type',
          options: [],
        },
        {
          label: '准驾车型',
          prop: 'drivingType',
          filterable: true,
          type: 'select',
          dicUrl: '/api/blade-system/dict-biz/dictionary?code=basic_driving_type',
          options: [],
        },

        {
          label: '绑定车辆',
          prop: 'bindVehicles',
          filterable: true,
          type: 'select',
          remote: true,
          multiple: true,
          // dicData: [],
          dicUrl: '/api/logpm-basicdata/vehicle/dictionary?vehicleNub={{key}}',
          options: [],
          multiple: true,
        },
        {
          label: '合同开始时间',
          prop: 'contractStartTime',
          type: 'date',
          format: 'YYYY-MM-DD',
          valueFormat: 'YYYY-MM-DD',
        },
        {
          label: '合同结束时间',
          prop: 'contractEndTime',
          type: 'date',
          format: 'YYYY-MM-DD',
          valueFormat: 'YYYY-MM-DD',
        },
        {
          label: '身份证号',
          prop: 'idCard',
          type: 'number',
        },
        {
          label: '性别',
          prop: 'gender',
          filterable: true,
          type: 'select',

          dicUrl: '/api/blade-system/dict-biz/dictionary?code=sex',
          options: [],
        },
        {
          label: '仓库',
          prop: 'warehouseIds',
          filterable: true,
          type: 'select',
          remote: true,
          dicUrl: '/logpm-basicdata/warehouse/listName?name={{key}}',
          options: [],
          rules: [{ required: true, message: '请选择仓库!', trigger: 'blur' }],
          multiple: true,
        },
        {
          label: '居住地址',
          prop: 'residentialAddress',
          type: 'input',
        },
        {
          label: '银行类型',
          prop: 'bankType',
          filterable: true,
          type: 'select',
          dicUrl: '/api/blade-system/dict-biz/dictionary?code=basic_bank_type',
          options: [],
        },
        {
          label: '银行卡号',
          prop: 'bankCardNub',
          type: 'number',
        },
        {
          label: '驾驶证号',
          prop: 'driverLicenseNub',
          type: 'input',
        },
        {
          label: '驾驶证发证机关',
          prop: 'driverLicenseOrgan',
          type: 'input',
        },
        {
          label: '驾驶证起始日期',
          prop: 'driverLicenseStartTime',
          type: 'date',
          format: 'YYYY-MM-DD',
          valueFormat: 'YYYY-MM-DD',
        },
        {
          label: '驾驶证到期日期',
          prop: 'driverLicenseEndTime',
          type: 'date',
          format: 'YYYY-MM-DD',
          valueFormat: 'YYYY-MM-DD',
        },
        {
          label: '从业资格证编号',
          prop: 'employeeQualificationNub',
          type: 'input',
        },
        {
          label: '道路经营许可证号',
          prop: 'roadOperationLicenseNub',
          type: 'input',
        },
        {
          label: '承运商',
          prop: 'carrierId',
          filterable: true,
          type: 'select',
          filterable: true,
          dicUrl: '/api/logpm-basicdata/carrier/dictionary',
          options: [],
          rules: [{ required: true, message: '请选择承运商!', trigger: 'blur' }],
        },
        {
          label: '运输协议',
          prop: 'transportationAgreement',
          type: 'input',
        },
        {
          label: '备注',
          prop: 'notes',
          type: 'input',
        },
      ],
      imgOption: [
        {
          label: '人证合照照片',
          prop: 'licensePeoplePhoto',
          type: 'upload',
          dataType: 'string',
          listType: 'picture-img',
          hide: true,
          multiple: false,
          action: '/blade-resource/oss/endpoint/put-file',
          propsHttp: {
            res: 'data',
            url: 'link',
          },
        },
        {
          label: '身份证正面照片',
          prop: 'idCardFrontPhoto',
          type: 'upload',
          dataType: 'string',
          listType: 'picture-img',
          hide: true,
          multiple: false,
          action: '/blade-resource/oss/endpoint/put-file',
          propsHttp: {
            res: 'data',
            url: 'link',
          },
        },
        {
          label: '身份证背面照片',
          prop: 'idCardBackPhoto',
          type: 'upload',
          dataType: 'string',
          listType: 'picture-img',
          hide: true,
          multiple: false,
          action: '/blade-resource/oss/endpoint/put-file',
          propsHttp: {
            res: 'data',
            url: 'link',
          },
        },
        {
          label: '驾驶证照片',
          prop: 'driverLicensePhoto',
          type: 'upload',
          dataType: 'string',
          listType: 'picture-img',
          hide: true,
          multiple: false,
          action: '/blade-resource/oss/endpoint/put-file',
          propsHttp: {
            res: 'data',
            url: 'link',
          },
        },
        {
          label: '驾驶证背面照片',
          prop: 'driverLicensePhotoBack',
          type: 'upload',
          dataType: 'string',
          listType: 'picture-img',
          hide: true,
          multiple: false,
          action: '/blade-resource/oss/endpoint/put-file',
          propsHttp: {
            res: 'data',
            url: 'link',
          },
        },
      ],
      rules: {},
      /** 头部 */
      headers: {
        'Blade-Auth': 'bearer ' + getToken(),
      },
      shortcuts: [
        {
          text: '最近一周',
          value: () => {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            return [start, end];
          },
        },
        {
          text: '最近一个月',
          value: () => {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            return [start, end];
          },
        },
        {
          text: '最近三个月',
          value: () => {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            return [start, end];
          },
        },
      ],
      /** loading */
      loadingObj: {
        /** 表格loading */
        loading: false,
        /** 页面loading */
        pageLoading: false,
      },
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.basicdataDriverArtery_add, false),
      };
    },
  },
  async created() {
    console.log('created');
    try {
      this.loadingObj.pageLoading = true;

      await Promise.all([this.onLoad(), this.hanleOptions()]);
      this.rules = this.getRules();
    } catch (error) {
      console.log('error :>> ', error);
    } finally {
      this.loadingObj.pageLoading = false;
    }
  },
  methods: {
    /** 获取验证规则 */
    getRules() {
      const _rulesArr = {};

      for (let i = 0; i < this.option.length; i++) {
        const value = this.option[i];

        if (value.rules && value.rules.length > 0) {
          _rulesArr[value.prop] = value.rules;
        }

        return _rulesArr;
      }
    },
    /** 查询车辆绑定情况 */
    getVehiclede() {
      getVehicle().then(res => {
        console.log('车辆信息', res.data.data);
        res.data.data.map(v => {});
      });
    },
    /** 获取复选框的值 */
    async hanleOptions() {
      const res = await Promise.all([
        // 司机类型
        getDictionaryBiz('basic_driver_type'),
        // 职务类型
        getDictionaryBiz('basic_driverjob_type'),
        // 准驾车型
        getDictionaryBiz('basic_driving_type'),
        // 性别
        getDictionaryBiz('sex'),
        // 银行类型
        getDictionaryBiz('basic_bank_type'),
        // 绑定车辆
        getVehicle(),
        // 仓库
        getListName({ name: '' }),
        // 承运商
        getDictionary(),
      ]);

      const _nameArr = [
        '司机类型',
        '职务类型',
        '准驾车型',
        '性别',
        '银行类型',
        '绑定车辆',
        '仓库',
        '承运商',
      ];

      for (let i = 0; i < this.option.length; i++) {
        const value = this.option[i];

        const _index = _nameArr.indexOf(value.label);
        if (_index === -1) continue;
        const response = res[_index];
        console.log('response :>> ', response);
        const { code } = response.data;
        const data = response.data.data || [];

        if (code !== 200) continue;
        if (value.label === '绑定车辆') {
          const _data = [];

          for (let index = 0; index < data.length; index++) {
            _data.push({
              dictKey: data[index].id,
              dictValue: data[index].vehicleNub,
            });
          }

          value.options = _data;
        } else if (value.label === '仓库') {
          const _data = [];

          for (let index = 0; index < data.length; index++) {
            _data.push({
              dictKey: data[index].id,
              dictValue: data[index].name,
            });
          }
          value.options = _data;
        } else if (value.label === '承运商') {
          const _data = [];

          for (let index = 0; index < data.length; index++) {
            _data.push({
              dictKey: data[index].id,
              dictValue: data[index].carrierName,
            });
          }
          value.options = _data;
        } else value.options = data;
      }
      console.log('res :>> ', res);
    },
    /** 上传前 */
    handleBeforeUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      } else {
        return (isJPG || isPNG) && isLt2M;
      }

      /* let that = this;
      // ?通过FormData构造函数创建一个空对象
      let formData = new FormData();
      let reader = new FileReader();
      // ?将读取到的文件编码成DataURL
      reader.readAsDataURL(file);
      // ?压缩图片
      reader.onload = function (ev) {
        try {
          // ?读取图片来获得上传图片的宽高
          let img = new Image();
          img.src = ev.target.result;
          img.onload = function (ev) {
            // ?将图片绘制到canvas画布上进行压缩
            let canvas = document.createElement('canvas');
            let context = canvas.getContext('2d');
            let imgwidth = img.width;
            let imgHeight = img.height;
            // ?按比例缩放后图片宽高;
            let targetwidth = imgwidth;
            let targetHeight = imgHeight;
            // ?/如果原图宽大于最大宽度
            if (targetWidth > targetHeight) {
              // ?原图宽高比例
              let scale = targetHeight / 1280;
              targetHeight = 1280;
              targetWidth = targetwidth / scale;
            } else {
              // ?原图宽高比例
              let scale = targetWidth / 1280;
              targetWidth = 1280;
              targetHeight = targetHeight / scale;
            }
            // ?缩放后高度仍然大于最大高度继续按比例缩小
            canvas.width = targetwidth; //canvas的宽=图片的宽
            canvas.height = targetHeight; //canvas的高=图片的高
            context.clearRect(0, 0, canvas.width, canvas.height);
            context.drawImage(this, 0, 0, canvas.width, canvas.height);
            let data = '';
            // ?如果图片小于0.6Mb，不进行压缩，并返回二进制流
            if (file.size <= 628288) {
              data = canvas.toDataURL('image/jpeg');
              formData.append('file', file);
              that.handleChange(file);
            }
            // ?如果图片大于e.6Mb，进行压缩，并返回二进制流
            else {
              // todo 压缩文件大小比例
              data = canvas.toDataURL('image/jpeg', 0.4);
              let paper = that.GLOBAL.dataURLtoFile(data, file.name);
              formData.append('file', paper);
              console.log('paper :>> ', paper);
            }
          };
        } catch (error) {
          console.log('出现错误', error);
        }
      }; */
    },
    /** 上传成功 */
    handleUpLoadSuccess(file, item) {
      console.log('file :>> ', file);
      console.log(' this.form :>> ', this.form);
      if (file.code !== 200) return;
      this.form[item.prop] = file.data.link;
    },
    /** 移除图片 */
    handleRemoveImg(item) {
      delete this.form[item.prop];
    },
    handleImgError(item) {
      this.$message.error(item.label + '仅需上传一张图片');
    },
    handlePreview(file) {
      console.log('file :>> ', file);
    },
    async onLoad() {
      const _id = this.$route.query.id;
      if (!_id) return;
      const res = await getDetail(_id);

      const { code, data } = res.data;
      if (code !== 200) return;
      const _data = data;
      this.form = {
        ..._data,
      };

      this.form.bindVehicles = _data.bindVehicles && _data.bindVehicles.split(',');
      this.form.warehouseIds = _data.warehouses.map(val => val.warehouseId);
      console.log('_data :>> ', _data);
    },
    /** 新增 */
    async handleAdd() {
      try {
        this.loadingObj.pageLoading = true;

        const submitData = { ...this.form };
        submitData.bindVehicles = this.form.bindVehicles && this.form.bindVehicles.join(',');
        submitData.phone = this.form.phone.trim();

        const res = await add(submitData);
        const { code, msg } = res.data;
        if (code !== 200) return;
        this.$message.success(msg);

        ElMessageBox.confirm('是否继续添加?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          distinguishCancelAndClose: true,
          type: 'warning',
        })
          .then(() => {
            this.$refs.formRef.resetFields();
          })
          .catch(() => this.back());
      } catch (error) {
        console.log('error :>> ', error);
      } finally {
        this.loadingObj.pageLoading = false;
      }
    },
    /** 编辑 */
    async handleEdit() {
      try {
        this.loadingObj.pageLoading = true;

        const submitData = { ...this.form };
        submitData.bindVehicles = this.form.bindVehicles && this.form.bindVehicles.join(',');
        submitData.phone = this.form.phone.trim();

        const res = await update(submitData);
        const { code, msg } = res.data;
        if (code !== 200) return;
        this.$message.success(msg);

        this.back();
      } catch (error) {
        console.log('error :>> ', error);
      } finally {
        this.loadingObj.pageLoading = false;
      }
    },
    submitForm() {
      this.$refs.formRef.validate(async valid => {
        if (!valid) return;
        console.log('this.form :>> ', this.form);
        ElMessageBox.confirm('是否确定提交?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          const { type } = this.$route.query;
          // 新增
          if (type === 'add') this.handleAdd();
          else if (type === 'edit') this.handleEdit();
        });
      });
    },
    /** 重置 */
    handleReset() {
      ElMessageBox.confirm('是否重置数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        const { type } = this.$route.query;
        // 新增
        this.$refs.formRef.resetFields();
        if (type === 'edit') this.onLoad();
      });
    },
    back() {
      const { backPath } = this.$route.query;
      this.$store.commit('DEL_TAG_CURRENT');
      backPath ? this.$route.push({ path: backPath }) : this.$router.go(-1);
    },
  },
};
</script>

<style scoped lang="scss">
:deep(.header_search .el-date-editor.el-input__wrapper) {
  height: 100% !important;
}

// 标题
:deep(.el-divider__text.is-left) {
  font-size: 20px;
  font-weight: bold;
  color: var(--el-color-primary);
}

.w100 {
  width: 100% !important;
}

// 数字输入框
:deep(.el-input-number .el-input__inner) {
  text-align: left;
}

// 日期选择框
:deep(.el-date-editor--date) {
  width: 100% !important;
  height: 100% !important;
}

.img-container {
  display: flex;
  flex-wrap: wrap;
}

.avatar {
  width: 147px;
  height: 147px;
  display: block;
}

.upLoadImg_box {
  position: relative;

  .clearIcon {
    opacity: 0;
    position: absolute;
    right: 10px;
    top: 10px;
    transition: all 0.3s;
    width: 30px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    border-radius: 50%;
  }

  &:hover {
    .clearIcon {
      cursor: pointer;
      opacity: 1;
    }
  }
}

.submit_container {
  position: absolute;
  bottom: 20px;
  left: 0;
  width: 100%;
  text-align: center;
}
</style>
