<template>
  <el-dialog
    :title="'供应商资质管理 - ' + supplierName"
    :visible.sync="dialogVisible"
    width="1000px"
    append-to-body :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['resource:supplier:edit']"
        >新增资质</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="licenseList">
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column label="资质类型" align="center" prop="licenseType" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="资质编号" align="center" prop="licenseNo" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="发证机关" align="center" prop="issuingAuthority" :show-overflow-tooltip="true" width="180" />
      <el-table-column label="有效期开始" align="center" prop="validFrom" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.validFrom">{{ parseTime(scope.row.validFrom, '{y}-{m}-{d}') }}</span>
          <span v-else style="color: #909399;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="有效期结束" align="center" prop="validTo" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.validTo">{{ parseTime(scope.row.validTo, '{y}-{m}-{d}') }}</span>
          <span v-else style="color: #909399;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="到期状态" align="center" width="120">
        <template slot-scope="scope">
          <el-tooltip :content="getExpireDateTooltip(scope.row)" placement="top">
            <el-tag :type="getExpireDateStatus(scope.row).color" size="small">
              <i :class="getExpireDateStatus(scope.row).icon" style="margin-right: 4px;"></i>
              {{ getExpireDateStatus(scope.row).label }}
            </el-tag>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="附件" align="center" width="100">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.attachmentUrl"
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="viewAttachment(scope.row.attachmentUrl)"
          >查看</el-button>
          <span v-else style="color: #909399;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['resource:supplier:edit']"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['resource:supplier:edit']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 资质表单弹窗 -->
    <el-dialog :title="licenseTitle" :visible.sync="licenseOpen" width="700px" append-to-body>
      <el-form ref="licenseForm" :model="licenseForm" :rules="licenseRules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="资质类型" prop="licenseType">
              <el-input v-model="licenseForm.licenseType" placeholder="请输入资质类型" maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资质编号" prop="licenseNo">
              <el-input v-model="licenseForm.licenseNo" placeholder="请输入资质编号" maxlength="100" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="发证机关" prop="issuingAuthority">
              <el-input v-model="licenseForm.issuingAuthority" placeholder="请输入发证机关" maxlength="200" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="有效期开始日期" prop="validFrom">
              <el-date-picker
                v-model="licenseForm.validFrom"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择有效期开始日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="有效期结束日期" prop="validTo">
              <el-date-picker
                v-model="licenseForm.validTo"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择有效期结束日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="附件" prop="attachmentUrl">
              <el-upload
                :action="uploadUrl"
                :headers="uploadHeaders"
                :file-list="fileList"
                :on-success="handleFileUpload"
                :on-remove="handleFileRemove"
                :limit="1"
                :before-upload="beforeUpload"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传JPG/PNG/GIF/PDF/DOC/DOCX/XLS/XLSX文件，且不超过10MB</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="licenseForm.remark" type="textarea" placeholder="请输入备注" maxlength="500" :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitLicenseForm">确 定</el-button>
        <el-button @click="cancelLicenseForm">取 消</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import {
  listSupplierLicense,
  getSupplierLicense,
  addSupplierLicense,
  updateSupplierLicense,
  delSupplierLicense
} from '@/api/resource/supplier'
import { getToken } from '@/utils/auth'
import { openFile } from '@/utils/file'

export default {
  name: 'SupplierLicenseDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    supplierId: {
      type: Number,
      default: null
    },
    supplierName: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      dialogVisible: this.visible,
      loading: false,
      licenseList: [],
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      licenseOpen: false,
      licenseTitle: '',
      licenseForm: {},
      licenseRules: {
        licenseType: [
          { required: true, message: '资质类型不能为空', trigger: 'blur' },
          { max: 100, message: '资质类型长度不能超过100个字符', trigger: 'blur' }
        ],
        licenseNo: [
          { max: 100, message: '资质编号长度不能超过100个字符', trigger: 'blur' }
        ],
        issuingAuthority: [
          { max: 200, message: '发证机关长度不能超过200个字符', trigger: 'blur' }
        ],
        validTo: [
          {
            validator: (rule, value, callback) => {
              if (this.licenseForm.validFrom && value && new Date(value) <= new Date(this.licenseForm.validFrom)) {
                callback(new Error('有效期结束日期应晚于开始日期'))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ],
        remark: [
          { max: 500, message: '备注长度不能超过500个字符', trigger: 'blur' }
        ]
      },
      fileList: [],
      uploadUrl: process.env.VUE_APP_BASE_API + '/common/upload',
      uploadHeaders: {
        Authorization: 'Bearer ' + getToken()
      }
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val
      if (val && this.supplierId) {
        this.getList()
      }
    },
    dialogVisible(val) {
      this.$emit('update:visible', val)
    }
  },
  methods: {
    /** 查询资质列表 */
    getList() {
      this.loading = true
      listSupplierLicense(this.supplierId, this.queryParams).then(response => {
        this.licenseList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 新增资质 */
    handleAdd() {
      this.resetLicenseForm()
      this.licenseOpen = true
      this.licenseTitle = '新增资质'
    },
    /** 编辑资质 */
    handleUpdate(row) {
      this.resetLicenseForm()
      const licenseId = row.id
      getSupplierLicense(this.supplierId, licenseId).then(response => {
        const data = response.data || {}
        this.licenseForm = {
          id: data.id,
          licenseType: data.licenseType,
          licenseNo: data.licenseNo,
          issuingAuthority: data.issuingAuthority,
          validFrom: data.validFrom,
          validTo: data.validTo,
          attachmentUrl: data.attachmentUrl,
          remark: data.remark
        }
        // 设置文件列表
        if (data.attachmentUrl) {
          this.fileList = [{
            name: data.attachmentUrl.split('/').pop() || '附件',
            url: data.attachmentUrl
          }]
        } else {
          this.fileList = []
        }
        this.licenseOpen = true
        this.licenseTitle = '编辑资质'
      })
    },
    /** 删除资质 */
    handleDelete(row) {
      const licenseId = row.id
      this.$modal.confirm('是否确认删除该资质？').then(() => {
        return delSupplierLicense(this.supplierId, licenseId)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
        this.$emit('success')
      }).catch(() => {})
    },
    /** 提交资质表单 */
    submitLicenseForm() {
      this.$refs['licenseForm'].validate(valid => {
        if (valid) {
          // 确保 supplierId 被设置到表单数据中
          const formData = {
            ...this.licenseForm,
            supplierId: this.supplierId
          }
          if (this.licenseForm.id != undefined) {
            updateSupplierLicense(this.supplierId, this.licenseForm.id, formData).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.licenseOpen = false
              this.getList()
              this.$emit('success')
            })
          } else {
            addSupplierLicense(this.supplierId, formData).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.licenseOpen = false
              this.getList()
              this.$emit('success')
            })
          }
        }
      })
    },
    /** 取消资质表单 */
    cancelLicenseForm() {
      this.licenseOpen = false
      this.resetLicenseForm()
    },
    /** 重置资质表单 */
    resetLicenseForm() {
      this.licenseForm = {
        id: undefined,
        licenseType: undefined,
        licenseNo: undefined,
        issuingAuthority: undefined,
        validFrom: undefined,
        validTo: undefined,
        attachmentUrl: undefined,
        remark: undefined
      }
      this.fileList = []
      this.resetForm('licenseForm')
    },
    /** 获取到期日期状态 */
    getExpireDateStatus(license) {
      if (!license.validTo) {
        return { status: 'normal', label: '正常', color: 'success', icon: 'el-icon-success', days: null }
      }
      const today = new Date()
      today.setHours(0, 0, 0, 0)
      const validTo = new Date(license.validTo)
      validTo.setHours(0, 0, 0, 0)
      const diffDays = Math.ceil((validTo - today) / (1000 * 60 * 60 * 24))
      if (diffDays < 0) {
        return {
          status: 'expired',
          label: '已过期',
          color: 'danger',
          icon: 'el-icon-warning',
          days: Math.abs(diffDays)
        }
      } else if (diffDays <= 30) {
        return {
          status: 'warning',
          label: '即将到期',
          color: 'warning',
          icon: 'el-icon-warning',
          days: diffDays
        }
      } else {
        return {
          status: 'normal',
          label: '正常',
          color: 'success',
          icon: 'el-icon-success',
          days: diffDays
        }
      }
    },
    /** 获取到期日期提示信息 */
    getExpireDateTooltip(license) {
      const status = this.getExpireDateStatus(license)
      if (!license.validTo) {
        return '无有效期限制'
      }
      if (status.days === null) {
        return '正常'
      }
      if (status.status === 'expired') {
        return `已过期${status.days}天`
      } else if (status.status === 'warning') {
        return `还有${status.days}天到期`
      } else {
        return `还有${status.days}天到期`
      }
    },
    /** 文件上传前校验 */
    beforeUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10
      const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']
      const isValidType = validTypes.includes(file.type)
      if (!isValidType) {
        this.$modal.msgError('上传文件只能是 JPG/PNG/GIF/PDF/DOC/DOCX/XLS/XLSX 格式!')
        return false
      }
      if (!isLt10M) {
        this.$modal.msgError('上传文件大小不能超过 10MB!')
        return false
      }
      return true
    },
    /** 文件上传成功 */
    handleFileUpload(response, file, fileList) {
      if (response.code === 200) {
        this.licenseForm.attachmentUrl = response.url
        this.$modal.msgSuccess('上传成功')
      } else {
        this.$modal.msgError(response.msg || '上传失败')
      }
    },
    /** 文件删除 */
    handleFileRemove(file, fileList) {
      this.licenseForm.attachmentUrl = undefined
      this.fileList = []
    },
    /** 查看附件 */
    viewAttachment(url) {
      if (!url) {
        this.$modal.msgError('附件地址不存在')
        return
      }
      openFile(url)
    },
    /** 关闭弹窗 */
    handleClose() {
      this.resetLicenseForm()
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
    }
  }
}
</script>

<style scoped>
</style>