<template>
  <div class="app-container">
    <!-- 寻源需求 -->
    <el-form
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="auto" size="small"
    >
      <!-- 表单搜索 -->
      <el-row>
        <el-col :span="6">
          <el-form-item prop="contractName">
            <el-input
              v-model.trim="queryParams.contractName"
              style="width: 100%"
              clearable
              placeholder="请输入合同名称"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="contractCode">
            <el-input
              v-model.trim="queryParams.contractCode"
              style="width: 100%"
              clearable
              placeholder="请输入合同编号"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="createTime">
            <el-date-picker
              v-model="createTime"
              type="daterange"
              style="width: 100%"
              range-separator="-"
              value-format="YYYY-MM-DD"
              start-placeholder="更新开始日期"
              end-placeholder="更新结束日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <el-button class="primary-lease" type="primary" @click="getContractListData">查询</el-button>
            <el-button class="primary-lease" type="primary" @click="onReset">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="18">
          <el-form-item>
            <el-button class="primary-lease" type="primary" @click="addContract">合同新建</el-button>
            <a :href="uploadUrlTemp" download="安徽省机械化装备共享平台-协议模板">
              <el-button
                class="primary-lease"
                type="primary"
                style="margin-left: 20px"
              >模板下载</el-button>
            </a>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 表格 -->
    <el-table
      :data="qualityLis"
      show-overflow-tooltip
      :header-cell-style="{
        background: '#00a288',
        color: '#fff',
      }"
    >
      <el-table-column align="center" label="合同编码">
        <template scope="scope">
          <a style="color: blue">
            {{ scope.row.contractCode }}
          </a>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="contractName" label="合同名称"/>
      <el-table-column align="center" prop="status" label="状态">
        <template scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column align="center" label="合同附件">
        <template scope="scope">
          <a
            :href="scope.row.bmFileInfoList.length > 0 ? scope.row.bmFileInfoList[0].fileUrl : null"
            target="_blank"
            style="color: #00a288; text-decoration: underline"
          >查看</a>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="createTime" label="创建时间"/>
      <el-table-column align="center" prop="updateTime" label="更新时间"/>
      <el-table-column align="center" label="操作" :width="220">
        <template scope="scope">
          <el-button size="small" type="primary" @click="onContract(scope.row)">编辑</el-button>
          <el-button
            size="small"
            type="danger"
            @click="onDelete(scope.row.id)"
            v-if="scope.row.status == 0"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total="total"
      @pagination="getContractListData"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
    />

    <!-- 新增和修改弹框 -->
    <el-dialog
      :visible.sync="dialogVisibleSettlein"
      :title="settleinTitle"
      width="40%"
      destroy-on-close
      class="centered-dialog"
      :close-on-click-modal="false"
      @close="onDialogClose"
    >
      <el-form
        label-width="140px"
        ref="addAndEditFormRef"
        label-position="right"
        :model="addAndEditForm"
        :rules="addAndEditFormRules"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同模板名称：" prop="contractName">
              <el-input
                autocomplete="off"
                style="width: 850px"
                maxlength="30"
                v-model="addAndEditForm.contractName"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="1" style="margin-bottom: 0" class="upload-tip">
              支持格式：word.单个文件大小不能超过2M，最多可上传1个
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="附件" prop="fileInfoList">
              <div style="flex: 1">
                <UploadComponentNewTwo
                  :maxSize="2"
                  :max-limit="1"
                  width="100%"
                  height="100%"
                  :multiple="true"
                  :autoUpload="true"
                  :minLimit="addAndEditForm.fileInfoList.length"
                  :actionUrl="uploadUrl"
                  listType="text"
                  :justifyContent="`flex-start`"
                  @onFileChange="onFileChange"
                  :acceptTypeList="['.doc', '.docx']"
                >
                  <template slot="default">
                    <el-button
                      type="primary"
                      class="primary-lease"
                    >上传文件</el-button>
                  </template>
                </UploadComponentNewTwo>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template slot="footer">
        <div class="dialog-footer">
          <el-button type="primary" class="primary-lease" @click="onCancel">取消</el-button>
          <el-button class="primary-lease" type="primary" @click="onSubmit()">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>

// API导入
import {
  getContractListApi,
  addContractApi,
  editContractApi,
  delContractApi,
  updateStatus
} from '@/api/contract-manage/index'

export default {
  data() {
    return {
      // 上传相关
      uploadUrlTemp: '',
      uploadUrl: process.env.VUE_APP_API_URL + '/file/upload',

      // 表格数据
      qualityLis: [],
      total: 0,

      // 查询参数
      queryParams: {
        contractName: '',
        contractCode: '',
        startTime: '',
        endTime: '',
        pageSize: 10,
        pageNum: 1
      },

      // 日期选择
      createTime: [],

      // 表单数据
      addAndEditForm: {
        id: '',
        contractName: '',
        fileInfoList: [],
        fileInfoTempList: [],
        bmFileInfoList: []
      },

      // 表单验证规则
      addAndEditFormRules: {
        contractName: [{ required: true, message: '请输入合同名称', trigger: 'blur' }],
        fileInfoList: [{ required: true, message: '请上传合同附件', trigger: 'blur' }]
      },

      // 弹窗相关
      dialogVisibleSettlein: false,
      settleinTitle: ''
    }
  },
  mounted() {
    this.getContractListData()
    this.uploadUrlTemp = window.location.origin + '/iws/mall-view/contract-template-250224.docx'
  },
  methods: {
    // 获取合同列表
    async getContractListData() {
      if (this.createTime.length > 0) {
        this.queryParams.startTime = this.createTime[0]
        this.queryParams.endTime = this.createTime[1]
      }
      try {
        const { data: res } = await getContractListApi(this.queryParams)
        this.qualityLis = res.rows
        this.total = res.total
      } catch (error) {
        console.error('获取合同列表失败:', error)
      }
    },

    // 重置表单
    onReset() {
      this.createTime = []
      this.queryParams.startTime = ''
      this.queryParams.endTime = ''
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.$refs.queryFormRef.resetFields()
      this.getContractListData()
    },

    // 状态变更
    async handleStatusChange(row) {
      try {
        const res = await updateStatus({ id: row.id, status: row.status })
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: '状态修改成功'
          })
          await this.getContractListData()
        }
      } catch (error) {
        console.error('修改状态失败:', error)
        // 失败时回滚状态
        row.status = row.status === 1 ? 0 : 1
      }
    },

    // 新增合同
    addContract() {
      this.settleinTitle = '合同新建'
      this.dialogVisibleSettlein = true
    },

    // 编辑合同
    onContract(row) {
      this.addAndEditForm.id = row.id
      this.addAndEditForm.contractName = row.contractName
      this.settleinTitle = '合同修改'
      this.dialogVisibleSettlein = true
    },

    // 关闭弹窗
    onDialogClose() {
      this.$refs.addAndEditFormRef.resetFields()
      this.addAndEditForm.fileInfoTempList = []
      this.addAndEditForm.fileInfoList = []
      this.addAndEditForm.bmFileInfoList = []
      this.addAndEditForm.id = ''
      this.addAndEditForm.contractName = ''
    },

    // 文件上传变更
    onFileChange(fileList) {
      this.addAndEditForm.fileInfoTempList = []
      const origin = window.location.origin

      const fileListTemp = fileList.map(e => {
        let testUrl = ''
        if (process.env.VUE_APP_API_URL === '/proxyApi') {
          testUrl = e.url
        } else {
          testUrl = 'http://sgwpdm.ah.sgcc.com.cn/iws/ahbns/' + e.url
        }
        return {
          fileName: e.name,
          fileUrl: testUrl
        }
      })

      this.addAndEditForm.fileInfoTempList.push(...fileListTemp)
    },

    // 提交表单
    onSubmit() {
      this.addAndEditForm.fileInfoList = this.addAndEditForm.fileInfoTempList
      this.$refs.addAndEditFormRef.validate(async(valid) => {
        if (valid) {
          const SEN_API = this.settleinTitle === '合同修改' ? editContractApi : addContractApi
          this.addAndEditForm.bmFileInfoList = this.addAndEditForm.fileInfoList

          try {
            const res = await SEN_API(this.addAndEditForm)
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: '提交成功'
              })
              this.dialogVisibleSettlein = false
              this.getContractListData()
            }
          } catch (error) {
            console.error('提交失败:', error)
          }
        }
      })
    },

    // 删除合同
    async onDelete(id) {
      try {
        const res = await delContractApi({ id })
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: '删除成功'
          })
          this.getContractListData()
        }
      } catch (error) {
        console.error('删除失败:', error)
      }
    },

    // 取消操作
    onCancel() {
      this.dialogVisibleSettlein = false
    }
  }
}
</script>

<style lang="scss" scoped>
:deep .upload-tip .el-form-item__label {
  color: transparent;
}

.el-pagination {
  justify-content: flex-end;
  padding: 5px 0;
}

:deep .el-pagination.is-background .el-pager li.is-active {
  background-color: #3cb4a6;
}

:deep .el-form--inline .el-form-item {
  margin-right: 6px;
  width: 95%;
}

.app-container-content {
  :deep(.el-dialog) {
    display: flex !important;
    flex-direction: column !important;
    margin: 0 !important;
    position: absolute !important;
    top: 50% !important;
    left: 50% !important;
    transform: translate(-50%, -50%) !important;
    max-height: 100vh !important;

    .el-dialog__body {
      flex: 1;
      overflow-y: scroll !important;
    }

    .dialog-content {
      padding: 20px;
    }
  }
}

:deep(.el-overlay) {
  z-index: 99 !important;
}
</style>

