<template>
  <el-dialog 
    title="修改报销申请" 
    :visible.sync="visible" 
    :close-on-click-modal="false"
    class="NCC-dialog NCC-dialog_center" 
    width="1200px"
    @close="handleClose"
  >
    <div class="form-content" v-loading="loading">
      <el-form 
        ref="form" 
        :model="dataForm" 
        :rules="rules" 
        label-width="120px" 
        label-position="right"
      >
        <!-- 基本信息 -->
        <el-card class="form-card" shadow="hover">
          <div slot="header" class="card-header">
            <i class="el-icon-document"></i>
            <span class="card-title">基本信息</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="申请人" prop="applicationUserId">
                <user-select 
                  v-model="dataForm.applicationUserId" 
                  placeholder="请选择申请人" 
                  clearable
                  @change="handleUserChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请人姓名" prop="applicationUserName">
                <el-input 
                  v-model="dataForm.applicationUserName" 
                  placeholder="自动填充" 
                  readonly
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请门店" prop="applicationStoreId">
                <el-select 
                  v-model="dataForm.applicationStoreId" 
                  placeholder="请选择申请门店"
                  clearable
                  filterable
                  style="width: 100%"
                >
                  <el-option
                    v-for="store in storeOptions"
                    :key="store.id"
                    :label="store.dm"
                    :value="store.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请时间" prop="applicationTime">
                <el-date-picker
                  v-model="dataForm.applicationTime"
                  type="datetime"
                  placeholder="请选择申请时间"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="timestamp"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="总金额" prop="amount">
                <el-input 
                  v-model="dataForm.amount" 
                  placeholder="自动计算" 
                  readonly
                >
                  <template slot="prepend">¥</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 选择购买记录 -->
        <el-card class="form-card" shadow="hover">
          <div slot="header" class="card-header">
            <i class="el-icon-shopping-cart-full"></i>
            <span class="card-title">选择购买记录</span>
          </div>
          <div>
            <el-button 
              type="primary" 
              icon="el-icon-plus" 
              @click="openPurchaseDialog"
            >
              选择购买记录
            </el-button>
            <span v-if="selectedPurchaseRecords.length > 0" class="selected-count">
              已选择 {{ selectedPurchaseRecords.length }} 条记录
            </span>
          </div>
          
          <!-- 已选择的购买记录列表 -->
          <div v-if="selectedPurchaseRecords.length > 0" class="purchase-list">
            <el-table :data="selectedPurchaseRecords" border size="small">
              <el-table-column prop="reimbursementCategoryName" label="分类名称" />
              <el-table-column prop="unitPrice" label="单价" >
                <template slot-scope="scope">
                  ¥{{ formatMoney(scope.row.unitPrice) }}
                </template>
              </el-table-column>
              <el-table-column prop="quantity" label="数量"  />
              <el-table-column prop="amount" label="金额" >
                <template slot-scope="scope">
                  ¥{{ formatMoney(scope.row.amount) }}
                </template>
              </el-table-column>
              <el-table-column prop="purchaseTime" label="购买时间" width="180">
                <template slot-scope="scope">
                  {{ formatDateTime(scope.row.purchaseTime) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100" align="center">
                <template slot-scope="scope">
                  <el-button 
                    v-if="!scope.row.isInitial"
                    type="text" 
                    icon="el-icon-delete" 
                    @click="removePurchaseRecord(scope.$index)"
                    style="color: #F56C6C"
                  >
                    移除
                  </el-button>
                  <span v-else style="color: #909399; font-size: 12px;">初始记录</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button 
        type="primary" 
        @click="handleSubmit"
        :loading="submitting"
      >
        保存修改
      </el-button>
    </span>

    <!-- 选择购买记录弹窗 -->
    <el-dialog
      title="选择购买记录"
      :visible.sync="showPurchaseDialog"
      width="900px"
      append-to-body
    >
      <div class="purchase-dialog-content">
        <div class="purchase-search">
          <el-input
            v-model="purchaseSearchKeyword"
            placeholder="搜索分类名称"
            clearable
            @input="handlePurchaseSearch"
            style="width: 300px"
          >
            <el-button slot="append" icon="el-icon-search" @click="loadPurchaseRecords" />
          </el-input>
        </div>
        <el-table
          :data="purchaseRecordList"
          v-loading="purchaseLoading"
          @selection-change="handlePurchaseSelectionChange"
          border
          max-height="400"
        >
          <el-table-column type="selection" width="55"/>
          <el-table-column prop="reimbursementCategoryName" label="分类名称" />
          <el-table-column prop="unitPrice" label="单价" >
            <template slot-scope="scope">
              ¥{{ formatMoney(scope.row.unitPrice) }}
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量"  />
          <el-table-column prop="amount" label="金额" >
            <template slot-scope="scope">
              ¥{{ formatMoney(scope.row.amount) }}
            </template>
          </el-table-column>
          <el-table-column prop="purchaseTime" label="购买时间" width="180">
            <template slot-scope="scope">
              {{ formatDateTime(scope.row.purchaseTime) }}
            </template>
          </el-table-column>
        </el-table>
        <div class="purchase-pagination">
          <el-pagination
            @size-change="handlePurchaseSizeChange"
            @current-change="handlePurchaseCurrentChange"
            :current-page="purchaseQuery.currentPage"
            :page-sizes="[10, 20, 50]"
            :page-size="purchaseQuery.pageSize"
            layout="total, sizes, prev, pager, next"
            :total="purchaseTotal"
          />
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showPurchaseDialog = false">取 消</el-button>
        <el-button type="primary" @click="confirmPurchaseSelection">确 定</el-button>
      </span>
    </el-dialog>
  </el-dialog>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'EditDialog',
  data() {
    return {
      visible: false,
      loading: false,
      submitting: false,
      applicationId: null,
      storeOptions: [],
      dataForm: {
        applicationUserId: '',
        applicationUserName: '',
        applicationStoreId: '',
        applicationTime: null,
        amount: '0.00',
        selectedPurchaseRecordIds: []
      },
      rules: {
        applicationStoreId: [
          { required: true, message: '请选择申请门店', trigger: 'change' }
        ],
        applicationTime: [
          { required: true, message: '请选择申请时间', trigger: 'change' }
        ],
        amount: [
          { required: true, message: '总金额不能为空', trigger: 'blur' }
        ]
      },
      selectedPurchaseRecords: [],
      showPurchaseDialog: false,
      purchaseRecordList: [],
      purchaseLoading: false,
      purchaseSearchKeyword: '',
      purchaseQuery: {
        currentPage: 1,
        pageSize: 20,
        reimbursementCategoryName: ''
      },
      purchaseTotal: 0,
      purchaseSelection: [],
      initialPurchaseRecordIds: [] // 存储初始的购买记录ID列表
    }
  },
  created() {
    this.loadStoreOptions()
  },
  methods: {
    async init(id) {
      this.visible = true
      this.loading = true
      this.applicationId = id
      this.submitting = false
      
      // 重置表单
      this.dataForm = {
        applicationUserId: '',
        applicationUserName: '',
        applicationStoreId: '',
        applicationTime: null,
        amount: '0.00',
        selectedPurchaseRecordIds: []
      }
      this.selectedPurchaseRecords = []
      this.initialPurchaseRecordIds = [] // 重置初始记录ID列表
      
      // 加载详情数据
      await this.loadDetail(id)
    },

    async loadDetail(id) {
      try {
        const response = await request({
          url: `/api/Extend/LqReimbursementApplication/${id}`,
          method: 'GET'
        })

        if (response.code === 200 && response.data && response.data.form) {
          const formData = response.data.form
          const purchaseRecords = response.data.purchaseRecords || []
          
          // 填充表单数据
          this.dataForm = {
            applicationUserId: formData.applicationUserId || '',
            applicationUserName: formData.applicationUserName || '',
            applicationStoreId: formData.applicationStoreId || '',
            applicationTime: formData.applicationTime || null,
            amount: formData.amount || '0.00',
            selectedPurchaseRecordIds: purchaseRecords.map(record => record.id)
          }
          
          // 保存初始的购买记录ID列表
          this.initialPurchaseRecordIds = purchaseRecords.map(record => record.id)
          
          // 填充购买记录列表，标记初始记录
          this.selectedPurchaseRecords = purchaseRecords.map(record => {
            // 处理附件字段
            if (record.attachment) {
              try {
                record.attachment = typeof record.attachment === 'string' 
                  ? JSON.parse(record.attachment) 
                  : record.attachment
              } catch (e) {
                record.attachment = []
              }
            } else {
              record.attachment = []
            }
            // 标记为初始记录
            record.isInitial = true
            return record
          })
          
          // 计算总金额
          this.calculateAmount()
        } else {
          this.$message.error(response.msg || '获取详情失败')
          this.visible = false
        }
      } catch (error) {
        console.error('获取详情失败:', error)
        this.$message.error('获取详情失败')
        this.visible = false
      } finally {
        this.loading = false
      }
    },

    async loadStoreOptions() {
      try {
        const response = await request({
          url: '/api/Extend/LqMdxx',
          method: 'GET',
          data: {
            currentPage: 1,
            pageSize: 1000
          }
        })
        if (response.code === 200 && response.data && response.data.list) {
          this.storeOptions = response.data.list
        }
      } catch (error) {
        console.error('加载门店列表失败:', error)
      }
    },

    // 申请人改变时，自动填充申请人姓名
    handleUserChange(userId) {
      if (userId) {
        // 处理userId可能是字符串（逗号分隔）的情况，取第一个
        const userIdArray = typeof userId === 'string' 
          ? userId.split(',').filter(id => id && id.trim())
          : [userId]
        const actualUserId = userIdArray.length > 0 ? userIdArray[0] : userId
        
        // 获取用户信息
        request({
          url: '/api/permission/Users/' + actualUserId,
          method: 'GET',
        }).then(res => {
          if (res.code === 200 && res.data) {
            this.dataForm.applicationUserName = res.data.realName || res.data.userName || res.data.fullName || ''
            // 如果门店为空，自动填充用户的门店
            if (!this.dataForm.applicationStoreId && res.data.mdid) {
              this.dataForm.applicationStoreId = res.data.mdid
            }
          }
        }).catch(error => {
          console.error('获取用户信息失败:', error)
        })
      } else {
        // 清空申请人时，也清空姓名
        this.dataForm.applicationUserName = ''
      }
    },

    openPurchaseDialog() {
      this.showPurchaseDialog = true
      this.loadPurchaseRecords()
    },

    async loadPurchaseRecords() {
      this.purchaseLoading = true
      try {
        const params = {
          currentPage: this.purchaseQuery.currentPage,
          pageSize: this.purchaseQuery.pageSize,
          approveStatus: '未审批', // 只选择未审批的购买记录
          createUserStoreId: this.dataForm.applicationStoreId || '暂无',
        }
        if (this.purchaseSearchKeyword) {
          params.reimbursementCategoryName = this.purchaseSearchKeyword
        }
        const response = await request({
          url: '/api/Extend/LqPurchaseRecords',
          method: 'GET',
          data: params
        })
        if (response.code === 200 && response.data) {
          this.purchaseRecordList = response.data.list || []
          this.purchaseTotal = (response.data.pagination && response.data.pagination.Total) || 0
        }
      } catch (error) {
        console.error('加载购买记录失败:', error)
        this.$message.error('加载购买记录失败')
      } finally {
        this.purchaseLoading = false
      }
    },

    handlePurchaseSearch() {
      this.purchaseQuery.currentPage = 1
      this.loadPurchaseRecords()
    },

    handlePurchaseSelectionChange(selection) {
      this.purchaseSelection = selection
    },

    confirmPurchaseSelection() {
      // 合并新选择的记录，标记为非初始记录
      const newRecords = this.purchaseSelection.filter(item => {
        return !this.selectedPurchaseRecords.find(record => record.id === item.id)
      }).map(record => {
        // 标记新增的记录
        record.isInitial = false
        return record
      })
      this.selectedPurchaseRecords = [...this.selectedPurchaseRecords, ...newRecords]
      this.calculateAmount()
      this.showPurchaseDialog = false
      // 清空选择
      this.purchaseSelection = []
    },

    removePurchaseRecord(index) {
      const record = this.selectedPurchaseRecords[index]
      // 检查是否是初始记录，初始记录不允许移除
      if (record && record.isInitial) {
        this.$message.warning('初始购买记录不能移除')
        return
      }
      this.selectedPurchaseRecords.splice(index, 1)
      this.calculateAmount()
    },

    calculateAmount() {
      // 计算总金额
      let total = 0
      this.selectedPurchaseRecords.forEach(record => {
        total += Number(record.amount || 0)
      })
      this.dataForm.amount = total.toFixed(2)
      this.dataForm.selectedPurchaseRecordIds = this.selectedPurchaseRecords.map(record => record.id)
    },

    handlePurchaseSizeChange(val) {
      this.purchaseQuery.pageSize = val
      this.loadPurchaseRecords()
    },

    handlePurchaseCurrentChange(val) {
      this.purchaseQuery.currentPage = val
      this.loadPurchaseRecords()
    },

    async handleSubmit() {
      // 验证表单
      this.$refs.form.validate(async (valid) => {
        if (!valid) {
          return false
        }

        // 验证购买记录
        if (!this.selectedPurchaseRecords || this.selectedPurchaseRecords.length === 0) {
          this.$message.warning('请至少选择一条购买记录')
          return false
        }

        this.submitting = true
        try {
          // 准备提交数据（只传递有值的字段）
          const submitData = {
            id: this.applicationId
          }
          
          // 只添加有值的字段
          if (this.dataForm.applicationUserId) {
            submitData.applicationUserId = this.dataForm.applicationUserId
          }
          if (this.dataForm.applicationUserName) {
            submitData.applicationUserName = this.dataForm.applicationUserName
          }
          if (this.dataForm.applicationStoreId) {
            submitData.applicationStoreId = this.dataForm.applicationStoreId
          }
          if (this.dataForm.applicationTime) {
            submitData.applicationTime = this.dataForm.applicationTime
          }
          if (this.dataForm.amount) {
            submitData.amount = this.dataForm.amount
          }
          if (this.dataForm.selectedPurchaseRecordIds && this.dataForm.selectedPurchaseRecordIds.length > 0) {
            submitData.selectedPurchaseRecordIds = this.dataForm.selectedPurchaseRecordIds
          }

          // 调用 PUT 接口更新数据
          const response = await request({
            url: `/api/Extend/LqReimbursementApplication/${this.applicationId}`,
            method: 'PUT',
            data: submitData
          })

          if (response.code === 200) {
            this.$message.success('修改成功')
            
            // 修改成功后，自动重新提交审批
            try {
              const submitResponse = await request({
                url: `/api/Extend/LqReimbursementApplication/${this.applicationId}/Actions/SubmitApproval`,
                method: 'POST'
              })
              
              if (submitResponse.code === 200) {
                this.$message.success('已重新提交审批')
              } else {
                this.$message.warning('修改成功，但重新提交审批失败：' + (submitResponse.msg || '未知错误'))
              }
            } catch (error) {
              console.error('重新提交审批失败:', error)
              this.$message.warning('修改成功，但重新提交审批失败，请手动提交')
            }
            
            this.visible = false
            this.$emit('refresh')
          } else {
            this.$message.error(response.msg || '修改失败')
          }
        } catch (error) {
          console.error('修改失败:', error)
          this.$message.error('修改失败')
        } finally {
          this.submitting = false
        }
      })
    },

    handleClose() {
      this.visible = false
      this.$refs.form && this.$refs.form.resetFields()
      this.dataForm = {
        applicationUserId: '',
        applicationUserName: '',
        applicationStoreId: '',
        applicationTime: null,
        amount: '0.00',
        selectedPurchaseRecordIds: []
      }
      this.selectedPurchaseRecords = []
      this.initialPurchaseRecordIds = []
      this.applicationId = null
    },

    formatMoney(amount) {
      if (!amount) return '0.00'
      return Number(amount).toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })
    },

    formatDateTime(dateTime) {
      if (!dateTime) return '无'
      const date = new Date(dateTime)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}`
    }
  }
}
</script>

<style lang="scss" scoped>
.form-content {
  overflow-y: auto;
  padding: 0 10px;
}

.form-card {
  margin-bottom: 20px;

  .card-header {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 600;
    color: #303133;

    i {
      font-size: 18px;
      color: #409EFF;
    }

    .card-title {
      flex: 1;
    }
  }
}

.selected-count {
  margin-left: 12px;
  color: #67C23A;
  font-size: 14px;
}

.purchase-list {
  margin-top: 16px;
}

.purchase-dialog-content {
  .purchase-search {
    margin-bottom: 16px;
  }

  .purchase-pagination {
    margin-top: 16px;
    text-align: right;
  }
}
</style>

