<!--
@name: 承运商管理-证件资料
@author: 张泽贤
@time: 20223-02-22
@doc:
-->
<template>
  <div>
    <div style="text-align: right">
      <a-space v-show="listType !== 'view'">
        <p-button type="primary" @clickSync="onEdit({}, 'add')" :disabled="!selectedData.id && listType === 'list'">新增</p-button>
        <p-button type="primary" @click="onEnOrDis(10)" :disabled="!selectedRowKeys.length">启用</p-button>
        <p-button type="danger" @click="onEnOrDis(0)" :disabled="!selectedRowKeys.length">停用</p-button>
      </a-space>
    </div>
    <p-table
      ref="paperTable"
      dragle
      bordered
      autoColWidth
      row-key="id"
      :id="$route.meta.menuId + '_paperInfo'"
      :scroll="{ x: true }"
      :columns="mx_columns"
      :data-source.sync="dataSource"
      :remote-url="listRemoteUrl"
      :remoteData="listParams"
      :rowSelectType="2"
      :selectedRowKeys.sync="selectedRowKeys"
      :autoLoad="false"
    >
      <template slot="operation" slot-scope="text, record">
        <a-space>
          <a @click.stop="onEdit(record, 'view')">查看</a>
          <a @click.stop="onEdit(record, 'edit')">修改</a>
          <p-switch @change="toEnOrDis(record)" :checked="record.status === 10 ? true : false" size="small" v-if="record.status !== 5" />
        </a-space>
      </template>
    </p-table>

    <!-- 弹窗 -->
    <p-modal title="证件信息" width="900px" :visible="visible" :confirm-loading="confirmLoading" @ok="handleOk" @cancel="visible = false">
      <p-form-model ref="dialogForm" :model="dialogForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" class="plg-grid-from" :rules="rules">
        <a-row>
          <a-col :span="8">
            <p-form-model-item label="证件号码" prop="code">
              <div v-if="type === 'view'">{{ dialogForm.code }}</div>
              <p-input v-model="dialogForm.code" :disabled="type !== 'add'" v-else />
            </p-form-model-item>
          </a-col>
          <a-col :span="8">
            <p-form-model-item label="证件类型" prop="type">
              <div v-if="type === 'view'">{{ dialogForm.typeName }}</div>
              <p-select v-model="dialogForm.type" :options="options.PAPER_TYPE" :disabled="type !== 'add'" v-else />
            </p-form-model-item>
          </a-col>
          <a-col :span="8">
            <p-form-model-item label="发证机关" prop="issuingAuthority">
              <div v-if="type === 'view'">{{ dialogForm.issuingAuthority }}</div>
              <p-input v-model="dialogForm.issuingAuthority" :disabled="type === 'view'" v-else />
            </p-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <p-form-model-item label="发证日期" prop="issuingDate">
              <div v-if="type === 'view'">{{ dialogForm.issuingDate }}</div>
              <p-date-picker v-model="dialogForm.issuingDate" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD" style="width: 100%" :disabled="type === 'view'" v-else />
            </p-form-model-item>
          </a-col>
          <a-col :span="16">
            <p-form-model-item label="有效期" prop="startDate" :label-col="{ span: 3 }" :wrapper-col="{ span: 21 }">
              <div v-if="type === 'view'">{{ dialogForm.startDate }} ~ {{ dialogForm.endDate }}</div>
              <p-range-picker v-model="validityDate" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD" :placeholder="['开始日期', '结束日期']" style="width: 100%" :disabled="type === 'view'" v-else />
            </p-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <p-form-model-item label="备注" prop="memo" :label-col="{ span: 2 }" :wrapper-col="{ span: 22 }">
              <div v-if="type === 'view'">{{ dialogForm.memo }}</div>
              <p-textarea v-model="dialogForm.memo" :disabled="type === 'view'" :rows="2" v-else />
            </p-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <p-form-model-item label="图片" prop="picture" :label-col="{ span: 2 }" :wrapper-col="{ span: 22 }">
              <a-upload
                :remove="handleRemove"
                list-type="picture-card"
                :before-upload="beforeUpload"
                :file-list="fileList"
                accept="image/jpeg,image/png"
                @preview="handlePreview"
                :showUploadList="{ showRemoveIcon: type !== 'view' }"
                @change="handleChange"
              >
                <div v-if="type !== 'view' && fileList.length < 4">
                  <a-icon type="plus" />
                  <div class="ant-upload-text">上传图片</div>
                </div>
              </a-upload>
            </p-form-model-item>
          </a-col>
        </a-row>
      </p-form-model>
    </p-modal>
    <p-modal ref="imgView" :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </p-modal>
  </div>
</template>

<script>
import { UPCLOUD_RDC_TMS_IMAGE_HOST } from '@/config/serviceSettings.js';
import { getLabelFromValue } from '@/blocks/utils';

import { pageCarrierPaper, whetherEnableCarrierPaper, addCarrierPaper, updateCarrierPaper, getPaperId, updateImg } from '../js/api.js';
import { setPaperInfoColumns } from '../js/tableConfig.js';

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      return resolve(reader.result);
    };
    reader.onerror = (error) => reject(error);
  });
}

export default {
  props: {
    selectedData: {
      type: Object,
      default: () => ({}),
    },
    selectedId: {
      type: String,
      default: '',
    },
    options: {
      type: Object,
      default: () => ({}),
    },
    listType: {
      type: String,
      default: '', // add-新增 edit-修改 view-查看 list-列表页
    },
  },
  computed: {
    validityDate: {
      get() {
        return [this.dialogForm.startDate, this.dialogForm.endDate];
      },
      set(value) {
        this.$set(this.dialogForm, 'startDate', value.length ? value[0] + ' 00:00:00' : '');
        this.$set(this.dialogForm, 'endDate', value.length ? value[1] + ' 23:59:59' : '');
      },
    },
  },
  watch: {
    // 新增时获取默认证件id
    visible(value) {
      this.sVisible = value;
      if (value) {
        if (this.type === 'add') {
          getPaperId().then((res) => {
            if (res.success && res.data) {
              this.dialogForm.id = res.data;
            } else {
              this.$exception(res);
            }
          });
        }
      }
    },
  },
  mounted() {
    if (this.selectedId) {
      this.listParams = { carrierId: this.selectedId };
    }
  },
  data() {
    return {
      // 主表格
      dataSource: [],
      selectedRowKeys: [],
      listRemoteUrl: pageCarrierPaper,
      listParams: {},
      mx_columns: setPaperInfoColumns(this, this.tableExtendedField),
      tableExtendedField: [],

      type: '',
      visible: false,
      confirmLoading: false,
      dialogForm: {
        id: '',
        code: '',
        type: '',
        issuingAuthority: '',
        issuingDate: '',
        startDate: '',
        endDate: '',
        memo: '',
        picture: [],
      },
      rules: {
        code: [{ required: true, message: '证件号码不能为空', trigger: 'blur' }],
        type: [{ required: true, message: '证件类型不能为空', trigger: 'change' }],
        startDate: [{ required: true, message: '有效期不能为空', trigger: 'change' }],
      },

      cacheFile: [], // 待上传的图片
      fileList: [], // 表格上显示的图片
      basePicture: [], // 已有的图片

      previewVisible: false,
      previewImage: '',
    };
  },
  methods: {
    onSearch(nVal) {
      if (nVal) {
        this.listParams = { carrierId: nVal };
      } else {
        this.dataSource = [];
      }
    },

    onEdit(record, type) {
      this.type = type;
      if (type === 'add') {
        this.dialogForm = {
          id: '',
          code: '',
          type: '',
          issuingAuthority: '',
          issuingDate: '',
          startDate: '',
          endDate: '',
          memo: '',
          picture: [],
        };
      } else {
        this.dialogForm = { ...record };
        this.dialogForm.picture = this.dialogForm.picture ? this.dialogForm.picture.split(',') : [];
      }
      this.cacheFile = [];
      this.basePicture = [...this.dialogForm.picture];
      this.fileList = this.basePicture.map((str, index) => {
        return {
          uid: index,
          name: str,
          status: 'done',
          url: UPCLOUD_RDC_TMS_IMAGE_HOST + '/' + str,
        };
      });

      this.visible = true;
    },

    // 启用、停用
    onEnOrDis(status) {
      this.WhetherToEnable(whetherEnableCarrierPaper, { paperIdList: this.selectedRowKeys, status }, status === 10 ? '启用' : '停用');
    },
    toEnOrDis(record) {
      let request = {
        paperIdList: [record.id],
        status: record.status === 10 ? 0 : 10,
      };
      this.WhetherToEnable(whetherEnableCarrierPaper, request, record.status === 10 ? '停用' : '启用');
    },
    WhetherToEnable(method, idList, text) {
      let self = this;
      this.$confirm({
        title: '是否' + text + '?',
        onOk() {
          return new Promise((resolve, reject) => {
            method(idList)
              .then((res) => {
                if (res.success) {
                  self.$message.success(res.message);
                  self.$refs.paperTable.reload();
                } else {
                  self.$exception(res);
                }
                resolve();
              })
              .catch((res) => {
                self.$exception(res);
                resolve();
              });
          });
        },
      });
    },

    // 删除图片
    handleRemove(file) {
      this.basePicture = this.basePicture.filter((str) => {
        return str !== file.name;
      });
      this.fileList = this.fileList.filter((item) => {
        return item.name !== file.name;
      });
    },
    // 更新图片
    beforeUpload(file, fileList) {
      if (file.type === 'image/jpeg' || file.type === 'image/png') {
        this.cacheFile.push(file);
      } else {
        this.$exception({
          message: '图片格式不正确，请上传.jpg/.png文件',
        });
      }

      return false;
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    handleChange(obj) {
      const { fileList, file } = obj;
      if (file.status == 'removed') {
        this.cacheFile = this.cacheFile.filter((item) => {
          return item.uid !== file.uid;
        });
      }

      if (file.type === 'image/jpeg' || file.type === 'image/png') {
        this.fileList = fileList;
      }
    },

    // 保存
    handleOk() {
      if (this.type === 'view') {
        this.visible = false;
        return;
      }

      let _this = this;
      this.$refs.dialogForm.validate((valid) => {
        if (!valid) return;

        _this.confirmLoading = false;

        // 没有加入新图片，就行list的数据返回
        if (!_this.cacheFile.length) {
          if (_this.listType === 'list') {
            _this.onSave();
          } else {
            let paperData = { ..._this.dialogForm };
            paperData.typeName = getLabelFromValue(paperData.type, this.options.PAPER_TYPE);
            paperData.picture = paperData.picture.join();
            if (this.type === 'add') {
              _this.dataSource.push(paperData);
            } else {
              let index = _this.dataSource.findIndex((item) => item.id === paperData.id);
              _this.dataSource[index] = paperData;
            }

            _this.visible = false;
          }
        } else {
          let formData = new FormData();
          let userinfo = _this.$store.getters?.userInfo ?? null;
          let size = 0;
          _this.cacheFile.forEach((file) => {
            size = +file.size;
            formData.append('file', file);
          });
          if (size > 31457280) {
            alert('文件上传过大');
            _this.confirmLoading = false;
            return;
          }
          formData.append('directory', '/tms');
          formData.append('storageType', 0);
          formData.append('isFileName', 0);

          updateImg(this, formData)
            .then((response, reject) => {
              if (response.success) {
                let fileList = response.data.map((item) => {
                  const { id, path, fileName } = item;
                  return path;
                });
                _this.dialogForm.picture = _this.basePicture.concat(fileList);
                if (_this.listType === 'list') {
                  _this.onSave();
                } else {
                  let paperData = { ..._this.dialogForm };
                  paperData.typeName = getLabelFromValue(paperData.type, this.options.PAPER_TYPE);
                  paperData.picture = paperData.picture.join();
                  if (this.type === 'add') {
                    _this.dataSource.push(paperData);
                  } else {
                    let index = _this.dataSource.findIndex((item) => item.id === paperData.id);
                    _this.dataSource[index] = paperData;
                  }
                  _this.visible = false;
                }
              } else {
                _this.$exception(response);
              }
            })
            .finally(() => {
              _this.confirmLoading = false;
            });
        }
      });
    },

    onSave() {
      let request = { ...this.dialogForm };
      request.carrierId = this.selectedData.id;
      request.carrierCode = this.selectedData.code;
      request.carrierName = this.selectedData.name;
      request.picture = request.picture.join();

      if (this.type === 'add') {
        addCarrierPaper(request)
          .then((res) => {
            if (res.success) {
              this.visible = false;
              this.$message.success(res.message);
              this.$refs.paperTable.reload();
            } else {
              this.$exception(res);
            }
          })
          .finally(() => {
            this.confirmLoading = false;
          });
      } else {
        updateCarrierPaper(request)
          .then((res) => {
            if (res.success) {
              this.visible = false;
              this.$message.success(res.message);
              this.$refs.paperTable.reload();
            } else {
              this.$exception(res);
            }
          })
          .finally(() => {
            this.confirmLoading = false;
          });
      }
    },
  },
};
</script>