<template>
  <div class="approval-div">
    <div class="search-div">
      <div class="search-left">
        <Row class="mb10">
          <Col span="6">
            <span>申请类型：</span>
            <Select style="width: 70%;" v-model="searchForm.type" clearable>
              <Option v-for="item in typeOptions" :key="item.value" :value="item.value">{{ item.label }}</Option>
            </Select>
          </Col>
        </Row>
      </div>
      <div class="search-right">
        <Row>
            <Col span="12">
                <Button type="primary" @click="handleSearch">搜索</Button>
            </Col>
            <Col span="12">
                <Button style="margin-left: 8px" @click="handleReset">重置</Button>
            </Col>
        </Row>
      </div>
    </div>

    <Table
      :loading="tableLoading"
      :columns="columns"
      :data="tableData"
      stripe
      border
    >
      <template slot-scope="{ row }" slot="status">
        <div class="flex-div">
          <div class="circle-div1" v-if="row.deal_result === '0'"></div>
          <div class="circle-div2" v-if="row.deal_result === '1'"></div>
          <div class="circle-div3" v-if="row.deal_result === '2'"></div>
          <span style="padding-left: 10px;">{{ getStatusText(row.deal_result) }}</span>
        </div>
      </template>
      <template slot-scope="{ row }" slot="action">
        <div class="flex-div">
          <Button type="primary" size="small" class="mr5" @click="handleView(row)">查看</Button>
          <Button type="primary" size="small" class="mr5" @click="showEventInfo(row)">事件详情</Button>
          <Button v-if="row.deal_result === '0'" type="success" size="small" class="mr5" @click="handleApprove(row)">同意</Button>
          <Button v-if="row.deal_result === '0'" type="error" size="small" class="mr5" @click="handleReject(row)">驳回</Button>
        </div>
      </template>
    </Table>

    <!-- <Page class="page_style" :total="pageTotal" :current="pageNo" :page-size="pageSize" show-total show-sizer @on-change="handlePageChange" @on-page-size-change="handlePageSizeChange" /> -->

    <!-- 审批表单对话框 -->
    <Modal
      v-model="approvalModal.visible"
      :title="approvalModal.title"
      :closable="false"
      :mask-closable="false"
      :footer-hide="true"
    >
      <Form :model="approvalForm" :label-width="80" :rules="approvalRules" ref="approvalForm">
        <FormItem label="处理意见" prop="deal_desc" :required="approvalForm.deal_result === '2'">
          <Input v-model="approvalForm.deal_desc" type="textarea" :rows="4" placeholder="请输入处理意见" />
        </FormItem>
      </Form>
      <div class="modal-footer">
        <Button @click="handleApprovalCancel">取消</Button>
        <Button type="primary" :loading="approvalModal.loading" @click="handleApprovalSubmit">确定</Button>
      </div>
    </Modal>

    <!-- 查看详情对话框 -->
    <Modal
      v-model="viewModal.visible"
      title="申请详情"
      :footer-hide="true"
    >
      <div class="detail-content">
        <Row class="detail-item">
          <Col span="8" class="detail-label">申请编号：</Col>
          <Col span="16" class="detail-value">{{ viewData.event_id || '-' }}</Col>
        </Row>
        <Row class="detail-item">
          <Col span="8" class="detail-label">申请类型：</Col>
          <Col span="16" class="detail-value">{{ getTypeText(viewData.approve_type) }}</Col>
        </Row>
        <Row class="detail-item">
          <Col span="8" class="detail-label">申请原因：</Col>
          <Col span="16" class="detail-value">{{ viewData.approve_desc || '-' }}</Col>
        </Row>
        <Row class="detail-item" v-if="viewData.approve_type === '0'">
          <Col span="8" class="detail-label">延期天数：</Col>
          <Col span="16" class="detail-value">{{ viewData.approve_days || '-' }} 天</Col>
        </Row>
        <Row class="detail-item">
          <Col span="8" class="detail-label">申请时间：</Col>
          <Col span="16" class="detail-value">{{ viewData.approve_time || '-' }}</Col>
        </Row>
        <Row class="detail-item">
          <Col span="8" class="detail-label">申请人：</Col>
          <Col span="16" class="detail-value">{{ viewData.create_by || '-' }}</Col>
        </Row>
        <Row class="detail-item">
          <Col span="8" class="detail-label">审批状态：</Col>
          <Col span="16" class="detail-value">{{ getStatusText(viewData.deal_result) }}</Col>
        </Row>
        <Row class="detail-item">
          <Col span="8" class="detail-label">处理结果描述：</Col>
          <Col span="16" class="detail-value">{{ viewData.deal_desc || '-' }}</Col>
        </Row>
        <Row class="detail-item">
          <Col span="8" class="detail-label">审批人：</Col>
          <Col span="16" class="detail-value">{{ viewData.deal_user_id || '-' }}</Col>
        </Row>
      </div>
    </Modal>
  </div>
</template>

<script>
import { getEventApproveList, updateEventApprove } from '@/api/approval'
import { mapState } from 'vuex'

export default {
  name: 'MyApproval',
  data () {
    return {
      searchForm: {
        type: '',
        status: '',
        dateRange: []
      },
      typeOptions: [
        { value: '0', label: '申请延期' },
        { value: '1', label: '申请不回访' },
        { value: '2', label: '申请未办结' },
        { value: '3', label: '申请退回' }
      ],
      statusOptions: [
        { value: 'pending', label: '待审批' },
        { value: 'approved', label: '已通过' },
        { value: 'rejected', label: '已拒绝' }
      ],
      columns: [
        { type: 'index', title: '序号', width: 80, align: 'center' },
        { title: '纠纷编号', key: 'event_code', align: 'center' },
        { title: '申请类型',
          key: 'approve_type',
          align: 'center',
          render: (h, params) => {
            const typeMap = {
              '0': '申请延期',
              '1': '申请不回访',
              '2': '申请不办结',
              '3': '申请退回'
            }
            return h('span', typeMap[params.row.approve_type] || '未知')
          }
        },
        { title: '申请原因', key: 'approve_desc', align: 'center' },
        { title: '延期天数', key: 'approve_days', align: 'center' },
        { title: '申请时间', key: 'approve_time', align: 'center' },
        { title: '申请人', key: 'create_by', align: 'center' },
        { title: '状态', slot: 'status', align: 'center' },
        { title: '处理结果描述', key: 'deal_desc', align: 'center' },
        { title: '审批人', key: 'deal_user_id', align: 'center' },
        { title: '操作', slot: 'action', align: 'center', width: 400 }
      ],
      tableData: [],
      tableLoading: false,
      pageNo: 1,
      pageSize: 10,
      pageTotal: 0,
      approvalModal: {
        visible: false,
        title: '审批',
        loading: false,
        type: '' // approve 或 reject
      },
      approvalForm: {
        id: '',
        deal_desc: '',
        deal_result: ''
      },
      approvalRules: {
        deal_desc: [
          {
            required: true,
            message: '请输入处理意见',
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (this.approvalForm.deal_result === '2' && !value) {
                callback(new Error('驳回时必须填写处理意见'))
              } else {
                callback()
              }
            }
          },
          { min: 1, max: 500, message: '处理意见长度在1-500个字符之间', trigger: 'blur' }
        ]
      },
      viewModal: {
        visible: false
      },
      viewData: {
        event_id: '',
        approve_type: '',
        approve_desc: '',
        approve_time: '',
        create_by: '',
        deal_result: '',
        deal_desc: '',
        deal_user_id: ''
      }
    }
  },
  computed: {
    ...mapState({
      currentUserId: state => state.user.userId
    }),
    serverUserInfo () {
      return this.$store.state.user.severUserInfo
    }
  },
  methods: {
    getStatusColor (status) {
      const colorMap = {
        pending: 'blue',
        approved: 'green',
        rejected: 'red'
      }
      return colorMap[status] || 'blue'
    },
    getStatusText (status) {
      const textMap = {
        '0': '待审批',
        '1': '审批通过',
        '2': '已驳回'
      }
      return textMap[status] || '未知'
    },
    handleSearch () {
      this.pageNo = 1
      this.getList()
    },
    handleReset () {
      this.searchForm = {
        type: ''
      }
      this.handleSearch()
    },
    handlePageChange (page) {
      this.pageNo = page
      this.getList()
    },
    handlePageSizeChange (size) {
      this.pageSize = size
      this.pageNo = 1
      this.getList()
    },
    async getList () {
      this.tableLoading = true
      try {
        const params = {
          approve_type: this.searchForm.type || '',
          data_type: '2' // 2：我的审批
        }

        const res = await getEventApproveList(params)
        if (res.data.errcode === 0) {
          this.tableData = res.data.data
        } else {
          this.$Message.error(res.data.errmsg || '获取列表失败')
        }
      } catch (error) {
        console.error('获取列表失败:', error)
        this.$Message.error('获取列表失败')
      } finally {
        this.tableLoading = false
      }
    },
    handleApprove (row) {
      this.approvalModal.visible = true
      this.approvalModal.title = '审批 - 同意'
      this.approvalModal.type = 'approve'
      this.approvalForm = {
        id: row.id,
        deal_desc: '',
        deal_result: '1' // 1表示同意
      }
    },
    handleReject (row) {
      this.approvalModal.visible = true
      this.approvalModal.title = '审批 - 拒绝'
      this.approvalModal.type = 'reject'
      this.approvalForm = {
        id: row.id,
        deal_desc: '',
        deal_result: '2' // 2表示拒绝
      }
    },
    handleApprovalCancel () {
      this.approvalModal.visible = false
      this.$refs.approvalForm.resetFields()
    },
    async handleApprovalSubmit () {
      this.approvalModal.loading = true
      try {
        // 先进行表单验证
        const valid = await this.$refs.approvalForm.validate()
        if (!valid) {
          this.approvalModal.loading = false
          return
        }

        const params = {
          id: this.approvalForm.id,
          deal_desc: this.approvalForm.deal_desc,
          deal_result: this.approvalForm.deal_result
        }

        const res = await updateEventApprove(params)
        if (res.data.errcode === 0) {
          this.$Message.success('审批提交成功')
          this.approvalModal.visible = false
          this.getList() // 刷新列表
        } else {
          this.$Message.error(res.msg || '审批提交失败')
        }
      } catch (error) {
        console.error('审批提交失败:', error)
        this.$Message.error('审批提交失败')
      } finally {
        this.approvalModal.loading = false
      }
    },
    showEventInfo (row) {
      this.$router.push({
        name: 'contradictionRegisterAdd',
        params: {
          what: 'edit',
          id: row.event_id
        }
      })
    },
    handleView (row) {
      this.viewData = { ...row }
      this.viewModal.visible = true
    },
    getTypeText (type) {
      const typeMap = {
        '0': '申请延期',
        '1': '申请不回访',
        '2': '申请为办结',
        '3': '申请退回'
      }
      return typeMap[type] || '未知'
    }
  },
  mounted () {
    this.getList()
  }
}
</script>

<style scoped>
.approval-div {
  padding: 16px;
  background: #f5f6fa;
  min-height: calc(100vh - 88px);
}

.search-div {
  padding: 15px 30px 15px 15px;
  border: 1px solid skyblue;
  border-radius: 5px;
  background-color: #f6fdfd;
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
}

.search-left {
  width: 90%;
}

.search-right {
  width: 10%;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.mb10 {
  margin-bottom: 10px;
}

.mr5 {
  margin-right: 5px;
  white-space: nowrap;
}

.flex-div {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  gap: 5px;
}

.circle-div1 {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #2d8cf0;
}

.circle-div2 {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #19be6b;
}

.circle-div3 {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #ed4014;
}

.circle-div4 {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #909399;
}

.page_style {
  margin-top: 16px;
  text-align: right;
}

.modal-footer {
  text-align: right;
  margin-top: 20px;
}

.modal-footer .ivu-btn {
  margin-left: 8px;
}

.detail-content {
  padding: 10px;
}
.detail-item {
  margin-bottom: 16px;
}
.detail-label {
  color: #666;
  text-align: right;
  padding-right: 12px;
}
.detail-value {
  word-break: break-all;
}
</style>
