<template>
  <el-dialog
    :title="'征用协议管理 - ' + requisitionTitle"
    :visible.sync="dialogVisible"
    width="1200px"
    append-to-body :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-row :gutter="10" class="mb8" v-if="canEdit">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增协议</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="agreementList" border>
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column label="服务范围" align="center" prop="serviceScope" :show-overflow-tooltip="true" min-width="200" />
      <el-table-column label="计费方式" align="center" prop="billingType" width="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.requisition_billing_type" :value="scope.row.billingType" />
        </template>
      </el-table-column>
      <el-table-column label="单价" align="center" prop="unitPrice" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.unitPrice">{{ scope.row.currency || 'CNY' }} {{ scope.row.unitPrice }}</span>
          <span v-else style="color: #909399;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="币种" align="center" prop="currency" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.currency" :value="scope.row.currency || 'CNY'" />
        </template>
      </el-table-column>
      <el-table-column label="生效开始时间" align="center" prop="effectiveFrom" width="160">
        <template slot-scope="scope">
          <span v-if="scope.row.effectiveFrom">{{ parseTime(scope.row.effectiveFrom, '{y}-{m}-{d} {h}:{i}') }}</span>
          <span v-else style="color: #909399;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="生效结束时间" align="center" prop="effectiveTo" width="160">
        <template slot-scope="scope">
          <span v-if="scope.row.effectiveTo">{{ parseTime(scope.row.effectiveTo, '{y}-{m}-{d} {h}:{i}') }}</span>
          <span v-else style="color: #909399;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="协议条款" align="center" prop="terms" :show-overflow-tooltip="true" min-width="150" />
      <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="200" fixed="right" v-if="canEdit">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</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"
    />

    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">关 闭</el-button>
    </div>

    <!-- 协议表单弹窗 -->
    <el-dialog :title="agreementTitle" :visible.sync="agreementOpen" width="800px" append-to-body :close-on-click-modal="false">
      <el-form ref="agreementForm" :model="agreementForm" :rules="agreementRules" label-width="140px">
        <el-form-item label="服务范围" prop="serviceScope">
          <el-input v-model="agreementForm.serviceScope" type="textarea" placeholder="请输入服务范围" maxlength="500" :rows="3" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="计费方式" prop="billingType">
              <el-select v-model="agreementForm.billingType" placeholder="请选择计费方式" style="width: 100%">
                <el-option
                  v-for="dict in (dict.type.requisition_billing_type || [])"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="币种" prop="currency">
              <el-select v-model="agreementForm.currency" placeholder="请选择币种" style="width: 100%">
                <el-option
                  v-for="dict in (dict.type.currency || [])"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="单价" prop="unitPrice">
          <el-input-number
            v-model="agreementForm.unitPrice"
            :min="0"
            :precision="2"
            placeholder="请输入单价"
            style="width: 100%"
          >
            <template slot="prepend">{{ agreementForm.currency || 'CNY' }}</template>
          </el-input-number>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="生效开始时间" prop="effectiveFrom">
              <el-date-picker
                v-model="agreementForm.effectiveFrom"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择生效开始时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生效结束时间" prop="effectiveTo">
              <el-date-picker
                v-model="agreementForm.effectiveTo"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择生效结束时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="协议条款" prop="terms">
          <el-input v-model="agreementForm.terms" type="textarea" placeholder="请输入协议条款" maxlength="500" :rows="3" />
        </el-form-item>
        <el-form-item label="附件" prop="attachmentUrl">
          <el-upload
            :action="uploadUrl"
            :headers="uploadHeaders"
            :file-list="fileList"
            :on-success="handleUploadSuccess"
            :on-remove="handleRemoveFile"
            :before-upload="beforeUpload"
            :limit="1"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png/pdf文件，且不超过10MB</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="agreementForm.remark" type="textarea" placeholder="请输入备注" maxlength="500" :rows="2" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAgreementForm">确 定</el-button>
        <el-button @click="agreementOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import {
  listRequisitionAgreements,
  getRequisitionAgreement,
  addRequisitionAgreement,
  updateRequisitionAgreement,
  delRequisitionAgreement
} from '@/api/resource/requisition'
import { getToken } from '@/utils/auth'
import { openFile } from '@/utils/file'

export default {
  name: 'RequisitionAgreementDialog',
  dicts: ['requisition_billing_type', 'currency'],
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    requisitionId: {
      type: Number,
      default: null
    },
    requisitionTitle: {
      type: String,
      default: ''
    },
    requisitionStatus: {
      type: String,
      default: 'draft'
    }
  },
  data() {
    return {
      dialogVisible: this.visible,
      loading: false,
      agreementList: [],
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      agreementOpen: false,
      agreementTitle: '',
      agreementForm: {},
      fileList: [],
      uploadUrl: process.env.VUE_APP_BASE_API + '/common/upload',
      uploadHeaders: {
        Authorization: 'Bearer ' + getToken()
      },
      agreementRules: {
        billingType: [
          { required: true, message: '计费方式不能为空', trigger: 'change' }
        ],
        unitPrice: [
          { required: true, message: '单价不能为空', trigger: 'blur' }
        ],
        currency: [
          { required: true, message: '币种不能为空', trigger: 'change' }
        ],
        effectiveFrom: [
          { required: true, message: '生效开始时间不能为空', trigger: 'change' }
        ],
        serviceScope: [
          { max: 500, message: '服务范围长度不能超过500个字符', trigger: 'blur' }
        ],
        terms: [
          { max: 500, message: '协议条款长度不能超过500个字符', trigger: 'blur' }
        ],
        remark: [
          { max: 500, message: '备注长度不能超过500个字符', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    canEdit() {
      return this.requisitionStatus === 'draft' || this.requisitionStatus === 'approved'
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val
      if (val && this.requisitionId) {
        this.getList()
      }
    },
    dialogVisible(val) {
      this.$emit('update:visible', val)
    }
  },
  methods: {
    /** 查询协议列表 */
    getList() {
      this.loading = true
      listRequisitionAgreements(this.requisitionId, this.queryParams).then(response => {
        this.agreementList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 新增协议 */
    handleAdd() {
      this.resetAgreementForm()
      this.agreementTitle = '新增协议'
      this.agreementOpen = true
    },
    /** 编辑协议 */
    handleEdit(row) {
      getRequisitionAgreement(row.id).then(response => {
        const data = response.data || {}
        this.agreementForm = {
          id: data.id,
          requisitionId: this.requisitionId,
          serviceScope: data.serviceScope,
          billingType: data.billingType,
          unitPrice: data.unitPrice,
          currency: data.currency || 'CNY',
          effectiveFrom: data.effectiveFrom,
          effectiveTo: data.effectiveTo,
          terms: data.terms,
          attachmentUrl: data.attachmentUrl,
          remark: data.remark
        }
        // 设置文件列表
        if (data.attachmentUrl) {
          this.fileList = [{
            name: data.attachmentUrl.split('/').pop(),
            url: data.attachmentUrl
          }]
        } else {
          this.fileList = []
        }
        this.agreementTitle = '编辑协议'
        this.agreementOpen = true
      })
    },
    /** 删除协议 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除该协议？').then(() => {
        return delRequisitionAgreement(this.requisitionId, row.id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 提交协议表单 */
    submitAgreementForm() {
      this.$refs['agreementForm'].validate(valid => {
        if (valid) {
          if (this.agreementForm.id != undefined) {
            updateRequisitionAgreement(this.requisitionId, this.agreementForm.id, this.agreementForm).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.agreementOpen = false
              this.getList()
              this.$emit('success')
            })
          } else {
            addRequisitionAgreement(this.requisitionId, this.agreementForm).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.agreementOpen = false
              this.getList()
              this.$emit('success')
            })
          }
        }
      })
    },
    /** 重置协议表单 */
    resetAgreementForm() {
      this.agreementForm = {
        id: undefined,
        requisitionId: this.requisitionId,
        serviceScope: undefined,
        billingType: undefined,
        unitPrice: undefined,
        currency: 'CNY',
        effectiveFrom: undefined,
        effectiveTo: undefined,
        terms: undefined,
        attachmentUrl: undefined,
        remark: undefined
      }
      this.fileList = []
      this.resetForm('agreementForm')
    },
    /** 文件上传成功 */
    handleUploadSuccess(response, file) {
      if (response.code === 200) {
        this.agreementForm.attachmentUrl = response.url
        this.$modal.msgSuccess('上传成功')
      } else {
        this.$modal.msgError(response.msg || '上传失败')
      }
    },
    /** 移除文件 */
    handleRemoveFile() {
      this.agreementForm.attachmentUrl = undefined
    },
    /** 上传前校验 */
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isPDF = file.type === 'application/pdf'
      const isValidType = isJPG || isPDF
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isValidType) {
        this.$modal.msgError('上传文件只能是 JPG/PNG/PDF 格式!')
      }
      if (!isLt10M) {
        this.$modal.msgError('上传文件大小不能超过 10MB!')
      }
      return isValidType && isLt10M
    },
    /** 查看附件 */
    viewAttachment(url) {
      openFile(url)
    },
    /** 关闭对话框 */
    handleClose() {
      this.agreementList = []
      this.total = 0
      this.queryParams = {
        pageNum: 1,
        pageSize: 10
      }
    }
  }
}
</script>

