<template>
  <!-- 基础页面 -->
  <div class="app-container">
    <el-card v-show="showSearch" style="margin-bottom: 20px">
      <el-form :model="queryParams" ref="queryForm"  size="small" inline  label-width="100px" >

          <el-form-item label="需求单位" prop="useUnit">
            <el-input v-model="queryParams.useUnit" style="width: 200px" placeholder="请输入需求单位" :disabled="queryParams.status=='0'" clearable/>
          </el-form-item>

        <el-form-item label="使用项目" prop="proName">
          <el-input style="width: 200px" disabled v-model="queryParams.proName"/>
        </el-form-item>

        <el-form-item label="项目类型" prop="proType">
          <el-input style="width: 200px" disabled v-model="queryParams.proType"/>
        </el-form-item>
        <el-form-item label="电压等级" prop="voltageLevel">
          <el-input style="width: 200px" disabled v-model="queryParams.voltageLevel"/>
        </el-form-item>
        <el-form-item  label="项目所在省" prop="proProvince">
          <el-input style="width: 200px" disabled v-model="queryParams.proProvince"/>
        </el-form-item>
        <el-form-item label="项目所在市" prop="proCity">
          <el-input style="width: 200px" disabled v-model="queryParams.proCity"/>
        </el-form-item>
        <el-form-item label="项目所在区/县" prop="proCounty">
          <el-input style="width: 200px" disabled v-model="queryParams.proCounty"/>
        </el-form-item>
        </el-form>

    </el-card>

    <el-card>
      <el-row :gutter="10" class="mb8" justify="end">
        <el-col :span="4">
          <span style="font-size: 20px; font-weight: 800">自用审核列表</span>
        </el-col>
      </el-row>

      <el-table
        v-loading="isLoading"
        :data="tableList"
        highlight-current-row
        border
        stripe
        :max-height="650"
        style="width: 100%"
      >
        <el-table-column
          type="index"
          width="55"
          label="序号"
          align="center"
        />
        <el-table-column label="分类" align="center" prop="devType" :show-overflow-tooltip="true" >
            <template slot-scope="scope">
                <span v-if="scope.row.devType==1">{{ "装备" }}</span>
                <span v-if="scope.row.devType==2">{{ "工具" }}</span>
            </template>
        </el-table-column>
        <el-table-column label="类目" align="center" prop="category" :show-overflow-tooltip="true" />
        <el-table-column label="名称" align="center" prop="typeName" :show-overflow-tooltip="true" width="120px"/>
        <el-table-column label="规格型号" align="center" prop="typeModelName" :show-overflow-tooltip="true" />
        <el-table-column label="管理模式" align="center" prop="manageType" :show-overflow-tooltip="true" >
            <template slot-scope="scope">
                <span v-if="scope.row.manageType==0">{{ "编码设备" }}</span>
                <span v-if="scope.row.manageType==1">{{ "数量设备" }}</span>
            </template>
        </el-table-column>
        <el-table-column label="设备编码" align="center" prop="devCode" :show-overflow-tooltip="true" width="140px"/>
        <el-table-column label="当前库存" align="center" prop="storageNum" :show-overflow-tooltip="true" />
        <el-table-column label="申请数量" align="center" prop="num" :show-overflow-tooltip="true" />
        <el-table-column label="使用到期日期" align="center" width="250px" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <!-- 处理日期为 null/undefined 的情况，显示占位符；有值则拼接为 "开始日期 至 结束日期" 格式 -->
            {{
              scope.row.useStartTime && scope.row.useEndTime
                ? `${scope.row.useStartTime} 至 ${scope.row.useEndTime}`
                : '暂无时间段'
            }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 审批进度 -->
      <div v-if="showApprovalProgress && processConfig && processConfig.nodeList" style="margin-top: 30px">
        <div style="margin-bottom: 15px; font-weight: bold;">审批进度</div>
        <el-timeline>
          <el-timeline-item
            v-for="node in processConfig.nodeList"
            :key="node.id"
            :timestamp="getNodeRecord(node) ? getNodeRecord(node).approveTime : ''"
            placement="top"
            :type="getNodeTagType(node)"
          >
            <p>
              <strong>{{ node.nodeName }}</strong>
              <span style="margin-left: 20px">{{ getNodeStatusLabel(node) }}</span>
            </p>
            <p v-if="getNodeRecord(node)">
              审批人：{{ getNodeRecord(node).approverName }}
            </p>
            <p v-if="getNodeRecord(node)">
              审批意见：{{ getNodeRecord(node).approveOpinion }}
            </p>
          </el-timeline-item>
        </el-timeline>
      </div>

      <!-- 审批操作 -->
      <div v-if="showApprovalActions && canApprove" style="margin-top: 30px">
        <div style="margin-bottom: 15px; font-weight: bold;">审批操作</div>
        <el-form ref="approveForm" :model="approveData" label-width="100px">
          <el-form-item label="审批意见">
            <el-input
              v-model="approveData.opinion"
              type="textarea"
              rows="4"
              placeholder="请输入审批意见"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>
          <el-form-item>
            <el-button type="success" @click="handlePass">通过</el-button>
            <el-button type="danger" @click="handleFail">驳回</el-button>
            <el-button @click="handleCancel">取消</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 返回按钮 -->
      <div v-if="showApprovalActions && !canApprove" style="margin-top: 30px">
        <el-button @click="handleCancel">返回</el-button>
      </div>
    </el-card>

  </div>
</template>

<script>
import { getApplyDetailsApi,applyPassApi } from '@/api/business'
import {
  getUseProjectListAPI,
  getVoltageListAPI,
} from '@/api/EquipmentLedger/equ-out'
import { regionData } from 'element-china-area-data'
import { getApprovalInstanceByBusiness, getApprovalDetail, getProcessConfig, doApprove } from '@/api/approval'
import { getCurrentUserId } from '@/utils/auth'


export default {
  name: 'AddEditApply',
  // components: { AddNum, AddCode },
  data() {
    return {
      routerParams: {},
      isLoading: false,
      showSearch: true,
      timeRange: [],
      queryParams: {
        type: 2, // 出库
        status: '0', // 变更状态
        proCode: '', // 使用项目id
        proName: '', // 使用项目名称
        proType: '', // 项目类型
        voltageLevel: '', // 电压等级
        proProvince: '', // 项目所在省
        proCity: '', // 项目所在市
        proCounty: '', // 项目所在区/县
        proLocation: '', // 详细地址
        useUnit: '', // 需求单位
        useTime:null,
        pageNum: 1, // 页码
        pageSize: 10, // 每页条数
      },
      useProjectList: [], // 使用项目下拉选
      voltageList: [], // 电压等级下拉选
      provinceList: [],
      cityList: [],
      countyList: [],

      typeList: [
        { label: '数量管理', value: '1' },
        { label: '编码管理', value: '0' },
      ],
      total: 0, // 总条数
      // 表格数据
      tableList: [],
      openAdd: false, // 添加申请
      addQuery: { // 添加申请查询
        typeName: '', // 名称
        typeModelName: '', // 规格型号
        devCode: '', // 设备编码
        pageNum: 1, // 页码
        pageSize: 10, // 每页条数
      },
      addTotal: 0, // 总条数
      addList: [], // 添加申请列表
      addTempList: [], // 添加申请临时列表
      ids: [], // 选中的id
      single: false, // 单选
      multiple: false, // 多选
      // 审批流相关数据
      approvalInstance: {},
      processConfig: null,
      canApprove: false,
      approveData: {
        opinion: ''
      },
      showApprovalProgress: false,
      showApprovalActions: false
    }
  },
  created() {
    this.routerParams = this.$route.query
    let title = '审核'
    if (this.routerParams.isView) {
      title = '查看审核'
    } else if (this.routerParams.isEdit) {
      title = '审核详情'
    }
    this.queryParams.id = this.routerParams.id || ''
    this.getUseProjectList()
    this.queryParams.status == '0' ? this.queryParams.useUnit = sessionStorage.getItem('deptName') : ''
    this.provinceList = regionData
    const obj = Object.assign({}, this.$route, { title })
    this.$tab.updatePage(obj)
    this.getList()
    // 加载审批信息
    this.loadApprovalInfo()
  },
  methods: {
    // 获取使用项目的下拉选
    async getUseProjectList() {
      const res = await getUseProjectListAPI()
      const result = await getVoltageListAPI()
      this.useProjectList = res.data
      this.voltageList = result.data
    },

    // 选择使用项目
    onChangeProCode(value) {
      this.queryParams.proCode = value
      this.queryParams.proName = this.useProjectList.find((item) => item.proCode === value)?.proName || ''
    },

    // 选择省份
    onChangeProvince(value) {
      if (!value) {
        this.cityList = []
        return
      }
      this.cityList = this.provinceList.find((item) => item.label === value)?.children || []
    },

    // 选择城市
    onChangeCity(value) {
      if (!value) {
        this.countyList = []
        return
      }
      this.countyList = this.cityList.find((item) => item.label === value)?.children || []
    },


    // 查询
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 重置
    handleReset() {
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.queryParams.parentId = '0'
      this.queryParams.level = '1'
      this.$refs.queryForm.resetFields()
      this.getList()
    },
    // 获取列表
    // 获取列表
    async getList(emit = {}) {
      console.log('🚀 ~ emit:', emit)
      if (emit.id) {
        this.queryParams.id = emit.id
        // 存到 route
        this.$route.query.id = this.queryParams.id
      }
      console.log('列表-查询', this.queryParams)
      this.isLoading = true
      try {
        const params = { ...this.queryParams }
        const res = await getApplyDetailsApi(params)
        this.tableList = res.data.devDetailsList || []
        if(this.queryParams.id){
        this.queryParams = res.data.devInfo || {}
        this.queryParams.status = '0'
        this.queryParams.useUnit = sessionStorage.getItem('deptName')
        }
        this.total = res.data.total || 0
      } catch (error) {
        this.tableList = []
        this.total = 0
      } finally {
        this.isLoading = false
      }
    },

    // 加载审批信息
    async loadApprovalInfo() {
      try {
        const businessId = this.routerParams.id || this.queryParams.id

        if (!businessId) {
          return
        }

        const instanceRes = await getApprovalInstanceByBusiness('EQUIPMENT_OUT', businessId)

        if (!instanceRes || !instanceRes.data) {
          return
        }

        const instanceId = instanceRes.data.id
        const processId = instanceRes.data.processId

        if (!instanceId || !processId) {
          return
        }

        // 查询审批详情
        const approvalRes = await getApprovalDetail(instanceId)
        if (approvalRes && approvalRes.data) {
          this.approvalInstance = approvalRes.data
          this.showApprovalProgress = true
          this.showApprovalActions = true

          // 查询流程配置
          const processRes = await getProcessConfig(processId)
          if (processRes && processRes.data) {
            this.processConfig = processRes.data
          }

          this.checkCanApprove()
        }
      } catch (error) {
        console.error('加载审批信息失败:', error)
      }
    },

    // 检查是否可以审批
    checkCanApprove() {
      // 状态0和1都表示审批中，可以进行审批
      if (this.approvalInstance.status !== '0' && this.approvalInstance.status !== '1') {
        this.canApprove = false
        return
      }

      const currentUserId = getCurrentUserId()

      if (this.processConfig && this.processConfig.nodeList) {
        const currentNode = this.processConfig.nodeList.find(
          node => node.id === this.approvalInstance.currentNodeId
        )

        if (currentNode && currentNode.approverIds) {
          const approverIds = currentNode.approverIds.split(',').map(id => parseInt(id))
          this.canApprove = approverIds.includes(parseInt(currentUserId))
        }
      }
    },

    // 获取节点记录
    getNodeRecord(node) {
      if (!this.approvalInstance.recordList) {
        return null
      }
      return this.approvalInstance.recordList.find(record => record.nodeId === node.id)
    },

    // 获取节点状态标签
    getNodeStatusLabel(node) {
      const record = this.getNodeRecord(node)
      if (record) {
        return record.approveResult === '1' ? '已通过' : '已驳回'
      }
      if (node.id === this.approvalInstance.currentNodeId) {
        return '审批中'
      }
      return '未开始'
    },

    // 获取节点标签类型
    getNodeTagType(node) {
      const record = this.getNodeRecord(node)
      if (record) {
        return record.approveResult === '1' ? 'success' : 'danger'
      }
      if (node.id === this.approvalInstance.currentNodeId) {
        return 'warning'
      }
      return 'info'
    },

    //通过
    handlePass() {
      if (!this.approveData.opinion) {
        this.$message.warning('请输入审批意见')
        return
      }

      this.$confirm('是否确定通过?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        try {
          await doApprove({
            instanceId: this.approvalInstance.id,
            approveResult: '1',
            approveOpinion: this.approveData.opinion
          })
          this.$message({
            type:'success',
            message: '审批通过成功!',
          })
          this.$router.go(-1)
        } catch (error) {
          this.$message.error('审批失败: ' + error.message)
        }
      })
    },

    // 驳回
    handleFail() {
      if (!this.approveData.opinion) {
        this.$message.warning('驳回时必须填写审批意见')
        return
      }

      this.$confirm('是否确定驳回?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        try {
          await doApprove({
            instanceId: this.approvalInstance.id,
            approveResult: '2',
            approveOpinion: this.approveData.opinion
          })
          this.$message({
            type:'success',
            message: '审批驳回成功!',
          })
          this.$router.go(-1)
        } catch (error) {
          this.$message.error('审批失败: ' + error.message)
        }
      })
    },

    handleCancel() {
      this.$router.go(-1)
    },

    handleBack() {
     this.$router.push({ path: '/business/auditList' })
    },




  },
}
</script>

<style lang="scss" scoped>
</style>
