<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-div4" v-if="!row.deal_result"></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>

        </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="applyModal.visible"
      :title="applyModal.title"
      :closable="false"
      :mask-closable="false"
      :footer-hide="true"
    >
      <Form :model="applyForm" :label-width="80" :rules="applyRules" ref="applyForm">
        <FormItem label="申请原因" prop="approve_desc">
          <Input v-model="applyForm.approve_desc" type="textarea" :rows="4" placeholder="请输入申请原因" />
        </FormItem>
        <FormItem label="延期天数" prop="approve_days" v-if="applyForm.approve_type === '0'">
          <InputNumber v-model="applyForm.approve_days" :min="1" :max="365" placeholder="请输入延期天数" :style="{width: '100%'}" />
        </FormItem>
      </Form>
      <div class="modal-footer">
        <Button @click="handleApplyCancel">取消</Button>
        <Button type="primary" :loading="applyModal.loading" @click="handleApplySubmit">确定</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, insertEventApprove } from '@/api/approval'
import { mapState } from 'vuex'

export default {
  name: 'MyApplication',
  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: '已拒绝' },
        { value: 'cancelled', 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: 'create_by', align: 'center' },
        { title: '延期天数', key: 'approve_days', align: 'center' },
        { title: '申请时间', key: 'approve_time', 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,
      applyModal: {
        visible: false,
        title: '新建申请',
        loading: false
      },
      applyForm: {
        approve_desc: '',
        approve_days: null
      },
      applyRules: {
        approve_desc: [
          { required: true, message: '请输入申请原因', trigger: 'blur' },
          { min: 1, max: 500, message: '申请原因长度在1-500个字符之间', trigger: 'blur' }
        ],
        approve_days: [
          {
            required: true,
            message: '请输入延期天数',
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (this.applyForm.approve_type === '0') {
                if (!value) {
                  callback(new Error('请输入延期天数'))
                } else if (value < 1 || value > 365) {
                  callback(new Error('延期天数必须在1-365天之间'))
                } else {
                  callback()
                }
              } else {
                callback()
              }
            }
          }
        ]
      },
      eventInfo: {
        deal_result_0: '',
        deal_result_1: '',
        deal_result_2: '',
        deal_result_3: '',
        completeTime: null,
        isAcceptance: '1',
        createBy: 'user456'
      },
      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',
        cancelled: 'gray'
      }
      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()
    },
    handleView (row) {
      this.viewData = { ...row }
      this.viewModal.visible = true
    },
    handleCancel (row) {
      // TODO: 实现撤回功能
      console.log('撤回申请', row)
    },
    async getList () {
      this.tableLoading = true
      try {
        const params = {
          approve_type: this.searchForm.type || '',
          data_type: '1' // 1：我的申请
        }

        const res = await getEventApproveList(params)
        console.log(res)
        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
      }
    },
    showApplyModal () {
      this.applyModal.visible = true
      this.applyForm = {
        event_id: '',
        approve_type: '',
        approve_desc: '',
        approve_days: null
      }
    },
    handleApplyCancel () {
      this.applyModal.visible = false
      this.$refs.applyForm.resetFields()
    },
    async handleApplySubmit () {
      this.applyModal.loading = true
      try {
        // 先进行表单验证
        const valid = await this.$refs.applyForm.validate()
        if (!valid) {
          this.applyModal.loading = false
          return
        }

        const params = {
          event_id: this.applyForm.event_id,
          approve_type: this.applyForm.approve_type,
          approve_desc: this.applyForm.approve_desc
        }

        // 如果是延期申请，添加延期天数
        if (this.applyForm.approve_type === '0') {
          params.approve_days = this.applyForm.approve_days
        }

        const res = await insertEventApprove(params)
        if (res.data.errcode === 0) {
          this.$Message.success('申请提交成功')
          this.applyModal.visible = false
          this.getList() // 刷新列表
        } else {
          this.$Message.error(res.msg || '申请提交失败')
        }
      } catch (error) {
        console.error('申请提交失败:', error)
        this.$Message.error('申请提交失败')
      } finally {
        this.applyModal.loading = false
      }
    },
    // 处理申请
    handleApply (row, type) {
      this.applyModal.visible = true
      this.applyForm = {
        event_id: row.event_id,
        approve_type: type,
        approve_desc: '',
        approve_days: null
      }
    },
    showEventInfo (row) {
      // 详情接口
      this.$router.push({
        name: 'contradictionRegisterAdd',
        params: {
          what: 'edit',
          id: row.event_id
        }
      })
    },
    getTypeText (type) {
      const typeMap = {
        '0': '申请延期',
        '1': '申请不回访',
        '2': '申请未办结',
        '3': '申请退回',
        '4': '退回'
      }
      return typeMap[type] || '未知'
    }
  },
  async 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;
}

.table-operations {
  margin-bottom: 16px;
}

.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>
