<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="自动填充" 
                  disabled
                  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 
                    type="text" 
                    icon="el-icon-delete" 
                    @click="removePurchaseRecord(scope.$index)"
                    style="color: #F56C6C"
                  >
                    移除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>

        <!-- 审批节点配置 -->
        <el-card class="form-card" shadow="hover">
          <div slot="header" class="card-header">
            <i class="el-icon-s-order"></i>
            <span class="card-title">审批节点配置（1-5个节点）</span>
            <el-button 
              type="text" 
              icon="el-icon-plus" 
              @click="addNode"
              style="margin-left: auto;"
              :disabled="dataForm.nodes.length >= 5"
            >
              添加节点
            </el-button>
          </div>
          <div class="nodes-list">
            <div 
              v-for="(node, index) in dataForm.nodes" 
              :key="index"
              class="node-item"
            >
              <div class="node-header">
                <span class="node-order">节点 {{ node.nodeOrder }}</span>
                <el-button 
                  type="text" 
                  icon="el-icon-delete" 
                  @click="removeNode(index)"
                  style="color: #F56C6C"
                  :disabled="dataForm.nodes.length <= 1"
                >
                  删除
                </el-button>
              </div>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item 
                    :label="`节点${node.nodeOrder}名称`" 
                    :prop="`nodes.${index}.nodeName`"
                    :rules="{ required: true, message: '请输入节点名称', trigger: 'blur' }"
                  >
                    <el-input 
                      v-model="node.nodeName" 
                      placeholder="请输入节点名称"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item 
                    :label="`节点${node.nodeOrder}类型`" 
                    :prop="`nodes.${index}.approvalType`"
                    :rules="{ required: true, message: '请选择审批类型', trigger: 'change' }"
                  >
                    <el-select 
                      v-model="node.approvalType" 
                      placeholder="请选择审批类型"
                      style="width: 100%"
                    >
                      <el-option label="会签" value="会签" />
                      <el-option label="或签" value="或签" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item 
                    :label="`节点${node.nodeOrder}审批人`" 
                    :prop="`nodes.${index}.approverIds`"
                    :rules="{ required: true, message: '请选择至少一个审批人', trigger: 'change' }"
                  >
                    <user-select 
                      v-model="node.approverIds" 
                      placeholder="请选择审批人" 
                      :multiple="true"
                      @change="(val) => handleApproverChange(index, val)"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="24" v-if="node.approverNames && node.approverNames.length > 0">
                  <el-form-item label="已选审批人">
                    <el-tag 
                      v-for="(name, nameIndex) in node.approverNames" 
                      :key="nameIndex"
                      style="margin-right: 8px;"
                    >
                      {{ name }}
                    </el-tag>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
            <div v-if="dataForm.nodes.length === 0" class="empty-nodes">
              <el-empty description="请添加审批节点（至少1个）" :image-size="80" />
            </div>
          </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'
import { getUserInfoList } from '@/api/permission/user'

export default {
  name: 'FormDialog',
  data() {
    return {
      visible: false,
      loading: false,
      submitting: false,
      storeOptions: [],
      dataForm: {
        applicationUserId: '',
        applicationUserName: '',
        applicationStoreId: '',
        applicationTime: null,
        amount: '0.00',
        selectedPurchaseRecordIds: [],
        nodes: []
      },
      rules: {
        applicationStoreId: [
          { required: true, message: '请选择申请门店', trigger: 'change' }
        ],
        applicationTime: [
          { required: true, message: '请选择申请时间', trigger: 'change' }
        ],
        amount: [
          { required: true, message: '总金额不能为空', trigger: 'blur' }
        ],
        selectedPurchaseRecordIds: [
          { required: true, message: '请至少选择一条购买记录', trigger: 'change', validator: this.validatePurchaseRecords }
        ]
      },
      selectedPurchaseRecords: [],
      showPurchaseDialog: false,
      purchaseRecordList: [],
      purchaseLoading: false,
      purchaseSearchKeyword: '',
      purchaseQuery: {
        currentPage: 1,
        pageSize: 20,
        reimbursementCategoryName: ''
      },
      purchaseTotal: 0,
      purchaseSelection: []
    }
  },
  created() {
    this.loadStoreOptions()
    // 初始化1个节点
    this.initNodes()
  },
  methods: {
    openPurchaseDialog() {
      this.showPurchaseDialog = true
      this.loadPurchaseRecords()
    },
    async init() {
      this.visible = true
      this.loading = false
      this.submitting = false
      
      // 获取当前登录用户信息
      const currentUser = this.$store.getters.userInfo
      const defaultUserId = currentUser && (currentUser.userId || currentUser.id) ? (currentUser.userId || currentUser.id) : ''
      const defaultUserName = currentUser && (currentUser.realName || currentUser.fullName || currentUser.userName) ? (currentUser.realName || currentUser.fullName || currentUser.userName) : ''
      
      this.dataForm = {
        applicationUserId: defaultUserId,
        applicationUserName: defaultUserName,
        applicationStoreId: '',
        applicationTime: new Date().getTime(),
        amount: '0.00',
        selectedPurchaseRecordIds: [],
        nodes: []
      }
      this.selectedPurchaseRecords = []
      this.initNodes()
      
      // 如果有默认用户，自动填充门店
      if (defaultUserId) {
        this.handleUserChange(defaultUserId)
      }
    },

    initNodes() {
      // 初始化1个节点
      this.dataForm.nodes = [
        {
          nodeOrder: 1,
          nodeName: '',
          approvalType: '',
          approverIds: '', // user-select组件期望字符串，不是数组
          approverNames: []
        }
      ]
    },

    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 || ''
            this.dataForm.applicationStoreId = res.data.mdid || ''
          }
        }).catch(error => {
          console.error('获取用户信息失败:', error)
        })
      } else {
        // 清空申请人时，也清空姓名和门店
        this.dataForm.applicationUserName = ''
        this.dataForm.applicationStoreId = ''
      }
    },

    addNode() {
      if (this.dataForm.nodes.length >= 5) {
        this.$message.warning('最多只能添加5个节点')
        return
      }
      const nextOrder = this.dataForm.nodes.length + 1
      this.dataForm.nodes.push({
        nodeOrder: nextOrder,
        nodeName: '',
        approvalType: '',
        approverIds: '', // user-select组件期望字符串，不是数组
        approverNames: []
      })
    },

    removeNode(index) {
      if (this.dataForm.nodes.length <= 1) {
        this.$message.warning('至少需要1个节点')
        return
      }
      this.dataForm.nodes.splice(index, 1)
      // 重新排序
      this.dataForm.nodes.forEach((node, idx) => {
        node.nodeOrder = idx + 1
      })
    },

    async handleApproverChange(index, userIds) {
      const node = this.dataForm.nodes[index]
      
      // user-select组件返回的是字符串（逗号分隔的ID）
      // 但我们需要保存为字符串格式，因为组件期望字符串
      const idsString = userIds || ''
      node.approverIds = idsString
      
      // 转换为数组用于获取用户名
      const idsArray = idsString ? idsString.split(',').filter(id => id && id.trim()) : []
      
      // 获取用户名列表
      if (idsArray.length > 0) {
        try {
          const response = await getUserInfoList(idsArray)
          if (response.code === 200 && response.data && response.data.list) {
            // 创建ID到用户信息的映射，确保顺序正确
            const userMap = new Map()
            response.data.list.forEach(user => {
              userMap.set(user.id, user.fullName || user.realName || user.id)
            })
            
            // 按照原始ID数组的顺序，从映射中取出对应的用户名
            node.approverNames = idsArray.map(id => {
              return userMap.get(id) || id
            })
          } else {
            node.approverNames = idsArray
          }
        } catch (error) {
          console.error('获取用户名失败:', error)
          // 如果获取失败，使用ID作为名称
          node.approverNames = idsArray
        }
      } else {
        node.approverNames = []
      }
      console.error(node)
    },

    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)
      })
      this.selectedPurchaseRecords = [...this.selectedPurchaseRecords, ...newRecords]
      this.calculateAmount()
      this.showPurchaseDialog = false
    },

    removePurchaseRecord(index) {
      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()
    },

    validatePurchaseRecords(rule, value, callback) {
      if (!this.selectedPurchaseRecords || this.selectedPurchaseRecords.length === 0) {
        callback(new Error('请至少选择一条购买记录'))
      } else {
        callback()
      }
    },

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

        // 验证节点数量
        if (this.dataForm.nodes.length < 1 || this.dataForm.nodes.length > 5) {
          this.$message.warning('审批节点数量必须在1-5个之间')
          return false
        }

        // 验证每个节点
        for (let i = 0; i < this.dataForm.nodes.length; i++) {
          const node = this.dataForm.nodes[i]
          if (!node.nodeName) {
            this.$message.warning(`请填写节点${node.nodeOrder}的名称`)
            return false
          }
          if (!node.approvalType) {
            this.$message.warning(`请选择节点${node.nodeOrder}的审批类型`)
            return false
          }
          // 验证审批人：approverIds可能是字符串（逗号分隔）或数组
          let approverIdsArray = []
          if (node.approverIds) {
            if (Array.isArray(node.approverIds)) {
              approverIdsArray = node.approverIds.filter(id => id)
            } else if (typeof node.approverIds === 'string') {
              approverIdsArray = node.approverIds.split(',').filter(id => id && id.trim())
            }
          }
          if (approverIdsArray.length === 0) {
            this.$message.warning(`请为节点${node.nodeOrder}选择至少一个审批人`)
            return false
          }
        }

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

        this.submitting = true
        try {
          // 准备提交数据
          const submitData = {
            applicationUserId: this.dataForm.applicationUserId || undefined,
            applicationUserName: this.dataForm.applicationUserName || undefined,
            applicationStoreId: this.dataForm.applicationStoreId,
            applicationTime: this.dataForm.applicationTime,
            amount: this.dataForm.amount,
            selectedPurchaseRecordIds: this.dataForm.selectedPurchaseRecordIds,
            nodes: this.dataForm.nodes.map(node => {
              // user-select组件返回的是字符串（逗号分隔），需要转换为数组
              let approverIds = []
              if (node.approverIds) {
                if (Array.isArray(node.approverIds)) {
                  approverIds = node.approverIds.filter(id => id)
                } else if (typeof node.approverIds === 'string') {
                  approverIds = node.approverIds.split(',').filter(id => id && id.trim())
                }
              }
              
              return {
                nodeOrder: node.nodeOrder,
                nodeName: node.nodeName,
                approvalType: node.approvalType,
                approverIds: approverIds,
                approverNames: node.approverNames && node.approverNames.length > 0 
                  ? node.approverNames 
                  : approverIds // 如果没有名称，使用ID
              }
            })
          }
          console.log(submitData)
          // return
          // 创建报销申请
          const response = await request({
            url: '/api/Extend/LqReimbursementApplication',
            method: 'POST',
            data: submitData
          })

          if (response.code === 200) {
            this.$message.success('创建成功')
            
            // 创建成功后，自动提交审批
            let applicationId = null
            if (response.data) {
              // 如果返回的是对象，取id字段
              if (typeof response.data === 'object' && response.data.id) {
                applicationId = response.data.id
              } else if (typeof response.data === 'string') {
                // 如果返回的是字符串，直接使用
                applicationId = response.data
              } else {
                // 如果返回的是其他类型，尝试转换为字符串
                applicationId = String(response.data)
              }
            }
            
            if (applicationId) {
              try {
                await request({
                  url: `/api/Extend/LqReimbursementApplication/${applicationId}/Actions/SubmitApproval`,
                  method: 'POST'
                })
                this.$message.success('已自动提交审批')
              } catch (error) {
                console.error('提交审批失败:', error)
                this.$message.warning('创建成功，但提交审批失败，请手动提交')
              }
            } else {
              this.$message.warning('创建成功，但无法获取申请ID，请手动提交审批')
            }
            
            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: new Date().getTime(),
        amount: '0.00',
        selectedPurchaseRecordIds: [],
        nodes: []
      }
      this.selectedPurchaseRecords = []
      this.initNodes()
    },

    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 {
 // max-height: 70vh;
  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;
}

.nodes-list {
  .node-item {
    padding: 16px;
    margin-bottom: 16px;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    background: #fafafa;

    .node-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      padding-bottom: 12px;
      border-bottom: 1px solid #e4e7ed;

      .node-order {
        font-weight: 600;
        color: #409EFF;
        font-size: 16px;
      }
    }
  }

  .empty-nodes {
    padding: 40px;
    text-align: center;
  }
}

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

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

