<!--
 * @Author: ysh
 * @Date: 2025-08-04 11:04:25
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-08-08 09:15:18
-->
<template>
  <view class="container">
    <mescroll-uni ref="mescrollRef" @init="mescrollInit" @down="downCallback" @up="upCallback" :down="downOption"
      :up="upOption" :fixed="false" :top="10" style="padding: 30rpx;">
      <view>
        <view v-for="(item, index) in declareList" :key="index" class="modern-card">
          <view class="modern-card-header">
            <view class="modern-card-title">
              <text class="project-number">{{ formatterProjectNumber(item) }}</text>
              <text class="project-name">{{ formatterProjectName(item) }}</text>
            </view>
          </view>

          <view class="modern-card-body">
            <view class="avatar-section">
              <view class="avatar">
                <text>{{ item.user && item.user.nickName ? item.user.nickName[0] : '' }}</text>
              </view>
              <view>
                <text class="applier-name">{{ item.user ? item.user.nickName : '' }}</text>
                <text class="dept-name">填报人</text>
              </view>
            </view>

            <view class="info-row">
              <text class="info-label">工作类别：</text>
              <text class="info-value">{{ item.workType }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">工作项目：</text>
              <text class="info-value">{{ item.workItem }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">工作内容：</text>
              <text class="info-value">{{ item.workContent }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">工作时间：</text>
              <text class="info-value">{{ item.beginDate }} ~ {{ item.endDate }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">工天数量：</text>
              <text class="info-value">{{ item.workLoad }}天</text>
            </view>
            <view class="info-row">
              <text class="info-label">工天单价：</text>
              <text>{{ item.price }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">系数：</text>
              <text class="info-value">{{ item.coefficient }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">预估绩效：</text>
              <text class="amount-highlight">￥{{ predictMoney(item) }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">填报时间：</text>
              <text class="info-value">{{ parseTime(item.submitTime, '{y}-{m}-{d}') }}</text>
            </view>

            <!-- 审核状态 -->
            <view class="status-section">
              <view class="status-item">
                <text class="status-label">一审：</text>
                <view class="status-tag" :class="formatFn(item, 'checkStatus') ? 'success' : 'warning'">
                  <text>{{ formatFn(item, 'checkStatus') ? '已通过' : '待审核' }}</text>
                </view>
              </view>
              <view class="status-item">
                <text class="status-label">二审：</text>
                <view class="status-tag" :class="formatFn(item, 'auditStatus') ? 'success' : 'warning'">
                  <text>{{ formatFn(item, 'auditStatus') ? '已通过' : '待审核' }}</text>
                </view>
              </view>
              <view class="status-item">
                <text class="status-label">确认：</text>
                <view class="status-tag" :class="formatFn(item, 'confirmStatus') ? 'success' : 'warning'">
                  <text>{{ formatFn(item, 'confirmStatus') ? '已确认' : '待确认' }}</text>
                </view>
              </view>
            </view>
          </view>

          <view class="modern-card-footer">
            <button class="footer-btn detail-btn" @click="openFormInfo(item)">表单信息</button>
            <button class="footer-btn form-btn" @click="handleUpdate(item)">修改</button>
          </view>
        </view>
      </view>
    </mescroll-uni>

    <!-- 修改对话框 -->
    <uni-popup ref="updatePopup" type="center" :mask-click="false">
      <view class="update-dialog">
        <view class="dialog-header">
          <text class="dialog-title">修改工作填报</text>
          <text class="dialog-close" @click="closeUpdateDialog">×</text>
        </view>

        <view class="dialog-body">
          <!-- 只读信息 -->
          <view class="readonly-section">
            <view class="info-item">
              <text class="info-label">项目编号：</text>
              <text class="info-value">{{ updateForm.projectNumber }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">项目名称：</text>
              <text class="info-value">{{ updateForm.projectName }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">填报人：</text>
              <text class="info-value">{{ updateForm.nickName }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">工作类别：</text>
              <text class="info-value">{{ updateForm.workType }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">工作项目：</text>
              <text class="info-value">{{ updateForm.workItem }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">工作内容：</text>
              <text class="info-value">{{ updateForm.workContent }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">工作时间：</text>
              <text class="info-value">{{ updateForm.beginDate }} ~ {{ updateForm.endDate }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">工天数量：</text>
              <text class="info-value">{{ updateForm.workLoad }}天</text>
            </view>
            <view class="info-item">
              <text class="info-label">工天单价：</text>
              <text class="info-value">￥{{ updateForm.price }}</text>
            </view>
          </view>

          <!-- 可修改的系数 -->
          <view class="edit-section">
            <view class="form-item">
              <text class="form-label">系数：</text>
              <uni-easyinput class="form-input" type="number" v-model="updateForm.coefficient"
                @input="calculatePredictMoney" @confirm="confirmUpdate" placeholder="请输入系数" :clearable="false"
                :trim="true" />
            </view>

            <!-- 预估绩效显示 -->
            <view class="predict-section">
              <text class="predict-label">预估绩效：</text>
              <text class="predict-amount">￥{{ predictMoney(updateForm) }}</text>
            </view>
          </view>
        </view>

        <view class="dialog-footer">
          <button class="dialog-btn cancel-btn" @click="closeUpdateDialog">取消</button>
          <button class="dialog-btn confirm-btn" @click="confirmUpdate">确认修改</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { listDeclare, getDeclare, updateDeclare } from '@/api/oa/declare/declare';
import MescrollMixin from '@/uni_modules/mescroll/components/mescroll-uni/mescroll-mixins.js'

export default {
  mixins: [MescrollMixin],
  data() {
    return {
      mescroll: null, // mescroll实例
      downOption: {
        auto: true,
        textOutOffset: '下拉刷新',
        textLoading: '加载中...'
      },
      upOption: {
        auto: false,
        page: { num: 1, size: 10 },
        noMoreSize: 5,
        empty: { tip: '暂无工作填报数据' },
        textNoMore: '~ 没有更多数据了 ~'
      },
      declareList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: null,
        userId: null,
        submitTime: null
      },
      // 修改表单数据
      updateForm: {
        formId: null,
        workType: '',
        workItem: '',
        workContent: '',
        beginDate: '',
        endDate: '',
        workLoad: 0,
        price: 0,
        coefficient: 0
      }
    }
  },

  onLoad: function (options) {
    uni.startPullDownRefresh();
  },

  methods: {
    // 加载数据
    async loadData() {
      try {
        // 权限控制逻辑
        if (this.$store.getters.deptId > 103) {
          this.queryParams.deptId = this.$store.getters.deptId;
        }
        if (this.$store.getters.roles.includes('projectLeader')) {
          this.queryParams.projectLeader = this.$store.getters.userId
        }
        if (this.$store.getters.roles.includes('dept')) {
          this.queryParams.projectLeader = null
        }
        if (this.$store.getters.userId == 1) {
          this.queryParams.deptId = null
          this.queryParams.projectLeader = null
        }

        const res = await listDeclare(this.queryParams)
        return { data: res.rows, total: res.total }
      } catch (e) {
        return { data: [], error: true }
      }
    },

    mescrollInit(mescroll) {
      this.mescroll = mescroll;
    },

    // mescroll下拉刷新回调
    async downCallback() {
      this.declareList = []; // 清空列表
      this.queryParams.pageNum = 1
      const res = await this.loadData()
      if (res.error) {
        this.mescroll.endErr();
      } else {
        this.declareList = res.data;
        this.mescroll.endSuccess(res.data.length, res.total);
      }
      uni.stopPullDownRefresh();
    },

    // mescroll上拉加载回调
    async upCallback(page) {
      this.queryParams.pageNum = page.num
      const res = await this.loadData()
      if (res.error) {
        this.mescroll.endErr();
      } else {
        this.declareList = this.declareList.concat(res.data)
        this.mescroll.endSuccess(res.data.length, res.total);
      }
    },

    // 格式化项目编号
    formatterProjectNumber(row) {
      if (!row.projectId) {
        return '无'
      } else {
        return row.project.projectNumber
      }
    },

    // 格式化项目名称
    formatterProjectName(row) {
      if (!row.projectId) {
        let year = row.submitTime.substring(0, 4)
        return year + '年借调、零星项目'
      } else {
        return row.project.projectName
      }
    },

    // 格式化状态
    formatFn(row, type) {
      if (row[type] && row[type] == '1') {
        return true
      } else {
        return false
      }
    },

    // 计算预估绩效
    predictMoney(row) {
      try {
        const price = parseFloat(row.price) || 0
        const workLoad = parseFloat(row.workLoad) || 0
        const coefficient = parseFloat(row.coefficient) || 0
        let result = price * workLoad * coefficient
        return result.toFixed(2)
      } catch (error) {
        console.log('计算预估绩效失败:', error)
        return '0.00'
      }
    },

    // 时间解析函数
    parseTime(time, cFormat) {
      if (!time) return ''

      const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
      let date
      if (typeof time === 'object') {
        date = time
      } else {
        if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
          time = parseInt(time)
        }
        date = new Date(time)
      }
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
      }
      const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
        const value = formatObj[key]
        if (key === 'a') {
          return ['日', '一', '二', '三', '四', '五', '六'][value]
        }
        return value.toString().padStart(2, '0')
      })
      return time_str
    },

    // 打开表单信息
    openFormInfo(item) {
      uni.navigateTo({
        url: `/pages/components/formInfo?formId=${item.formId}&formType=declare`
      });
    },

    // 修改操作
    handleUpdate(item) {
      console.log(item)
      // 填充修改表单数据
      this.updateForm = {
        formId: item.formId,
        projectNumber: item.project.projectNumber,
        projectName: item.project.projectName,
        nickName: item.user.nickName,
        workType: item.workType,
        workItem: item.workItem,
        workContent: item.workContent,
        beginDate: item.beginDate,
        endDate: item.endDate,
        workLoad: item.workLoad,
        price: item.price,
        coefficient: item.coefficient
      }

      // 打开修改对话框
      this.$refs.updatePopup.open()

      // 延迟聚焦到系数输入框（移动端兼容）
      this.$nextTick(() => {
        setTimeout(() => {
          try {
            // 查找uni-easyinput内部的input元素
            const input = document.querySelector('.form-input .uni-easyinput__content-input')
            if (input && typeof input.focus === 'function') {
              input.focus()
            }
          } catch (error) {
            console.log('聚焦输入框失败:', error)
          }
        }, 300)
      })
    },

    // 关闭修改对话框
    closeUpdateDialog() {
      this.$refs.updatePopup.close()
    },

    // 计算预估绩效（当系数改变时）
    calculatePredictMoney() {
      // 系数输入时自动触发计算，这里不需要额外处理
      // 因为模板中已经绑定了 predictMoney(updateForm)
    },

    // 确认修改
    async confirmUpdate() {
      try {
        // 验证系数
        if (!this.updateForm.coefficient || this.updateForm.coefficient <= 0) {
          uni.showToast({
            title: '请输入有效的系数',
            icon: 'none'
          })
          return
        }

        // 显示加载状态
        uni.showLoading({
          title: '修改中...'
        })

        // 调用更新接口
        await updateDeclare(this.updateForm)

        // 隐藏加载状态
        uni.hideLoading()

        uni.showToast({
          title: '修改成功',
          icon: 'success'
        })

        // 关闭对话框
        this.closeUpdateDialog()

        // 刷新列表
        this.downCallback()

      } catch (error) {
        // 隐藏加载状态
        uni.hideLoading()

        console.error('修改失败:', error)
        uni.showToast({
          title: '修改失败，请重试',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
  background-color: #f5f5f5;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.modern-card {
  background: #fff;
  border-radius: 18rpx;
  margin-bottom: 32rpx;
  box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.08);
  overflow: hidden;
  transition: box-shadow 0.2s;
  border: 1rpx solid #f0f0f0;
}

.modern-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(90deg, #e0e7ff 0%, #f8fafc 100%);
  padding: 24rpx 28rpx 16rpx 28rpx;
}

.modern-card-title {
  display: flex;
  flex-direction: column;
}

.project-number {
  font-size: 26rpx;
  color: #6366f1;
  font-weight: 600;
}

.project-name {
  font-size: 28rpx;
  color: #22223b;
  font-weight: bold;
  margin-top: 4rpx;
}

.amount-highlight {
  background: #fef3c7;
  color: #d97706;
  font-size: 28rpx;
  font-weight: bold;
  border-radius: 10rpx;
  padding: 8rpx 20rpx;
  min-width: 120rpx;
  text-align: center;
}

.amount-highlight-detail {
  background: #fef3c7;
  color: #d97706;
  font-size: 28rpx;
  font-weight: bold;
  border-radius: 10rpx;
  padding: 4rpx 18rpx;
  margin-left: 8rpx;
}

.modern-card-body {
  padding: 20rpx 28rpx 24rpx 28rpx;
}

.avatar-section {
  display: flex;
  align-items: center;
  margin-bottom: 18rpx;
}

.avatar {
  width: 56rpx;
  height: 56rpx;
  border-radius: 50%;
  background: #a5b4fc;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  font-weight: bold;
  margin-right: 18rpx;
}

.applier-name {
  font-size: 28rpx;
  color: #22223b;
  font-weight: 500;
}

.dept-name {
  font-size: 24rpx;
  color: #64748b;
  margin-left: 8rpx;
}

.info-row {
  display: flex;
  margin-bottom: 10rpx;
}

.info-label {
  color: #64748b;
  font-size: 24rpx;
  min-width: 120rpx;
}

.info-value {
  color: #22223b;
  font-size: 24rpx;
  flex: 1;
  word-break: break-all;
}

// 审核状态样式
.status-section {
  margin-top: 16rpx;
  padding-top: 16rpx;
  border-top: 1px solid #f0f0f0;
}

.status-item {
  display: flex;
  align-items: center;
  margin-bottom: 8rpx;
}

.status-label {
  color: #64748b;
  font-size: 24rpx;
  min-width: 80rpx;
}

.status-tag {
  padding: 4rpx 12rpx;
  border-radius: 6rpx;
  font-size: 22rpx;
  margin-left: 8rpx;
}

.status-tag.success {
  background: #dcfce7;
  color: #16a34a;
}

.status-tag.warning {
  background: #fef3c7;
  color: #d97706;
}

.modern-card-footer {
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
  padding: 16rpx 28rpx 20rpx 28rpx;
  border-top: 1px solid #f0f0f0;
  background: #fafbfc;
}

.footer-btn {
  font-size: 26rpx;
  border-radius: 8rpx;
  border: none;
  outline: none;
  background: #e0e7ff;
  color: #3b3b4f;
}

.detail-btn {
  background: #6366f1;
  color: #fff;
}

.form-btn {
  background: #f4c542;
  color: #fff;
}

// 修改对话框样式
.update-dialog {
  background: #fff;
  border-radius: 20rpx;
  width: 600rpx;
  max-height: 80vh;
  overflow: hidden;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 32rpx 32rpx 24rpx 32rpx;
  border-bottom: 1px solid #f0f0f0;
  background: linear-gradient(90deg, #e0e7ff 0%, #f8fafc 100%);
}

.dialog-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #22223b;
}

.dialog-close {
  font-size: 40rpx;
  color: #64748b;
  cursor: pointer;
  padding: 8rpx;
}

.dialog-body {
  padding: 32rpx;
  max-height: 60vh;
  overflow-y: auto;
}

.readonly-section {
  margin-bottom: 32rpx;
  padding-bottom: 24rpx;
  border-bottom: 1px solid #f0f0f0;
}

.info-item {
  display: flex;
  margin-bottom: 16rpx;
}

.edit-section {
  padding-top: 16rpx;
}

.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 24rpx;
}

.form-label {
  color: #64748b;
  font-size: 28rpx;
  min-width: 120rpx;
}

// uni-easyinput 样式调整
:deep(.uni-easyinput) {
  flex: 1;

  .uni-easyinput__content {
    border: 1px solid #e2e8f0 !important;
    border-radius: 8rpx !important;
    background: #fff !important;
    padding: 16rpx 20rpx !important;
  }

  .uni-easyinput__content-input {
    border: none !important;
    background: transparent !important;
    font-size: 28rpx !important;
    color: #22223b !important;
  }

  .uni-easyinput__content:focus-within {
    border-color: #6366f1 !important;
  }
}

.predict-section {
  display: flex;
  align-items: center;
  background: #fef3c7;
  padding: 20rpx;
  border-radius: 12rpx;
  margin-top: 16rpx;
}

.predict-label {
  color: #d97706;
  font-size: 28rpx;
  font-weight: 500;
}

.predict-amount {
  color: #d97706;
  font-size: 32rpx;
  font-weight: bold;
  margin-left: 16rpx;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
  padding: 24rpx 32rpx 32rpx 32rpx;
  border-top: 1px solid #f0f0f0;
  background: #fafbfc;
}

.dialog-btn {
  font-size: 28rpx;
  border-radius: 8rpx;
  border: none;
  outline: none;
  padding: 16rpx 32rpx;
  cursor: pointer;
}

.cancel-btn {
  background: #f1f5f9;
  color: #64748b;
}

.confirm-btn {
  background: #6366f1;
  color: #fff;
}

.confirm-btn:hover {
  background: #4f46e5;
}
</style>