<template>
  <div>
    <el-row>
      <el-col :span="6">
        <el-form-item
          label="报销日期："
        >
          <el-date-picker
            v-model="condition.time"
            type="month"
            placeholder="请选择报销月份"
            format="YYYY-MM"
            value-format="YYYY-MM"
            clearable
          />
        </el-form-item>
      </el-col>
      <el-col
        :span="6"
        :offset="1"
      >
        <el-form-item
          label="报销人："
        >
          <el-input
            v-model="condition.name"
            placeholder="请输入报销人"
            clearable
          />
        </el-form-item>
      </el-col>
      <el-col
        :span="2"
        :offset="1"
      >
        <el-button
          type="primary"
          :icon="Search"
          @click="searchReimburse"
        >查询</el-button>
      </el-col>
      <el-col
        :span="2"
        style="margin-left: 30px"
      >
        <el-button
          type="primary"
          :icon="Plus"
          @click="changeReimburseAddShow"
        >
          新增
        </el-button>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="23">
        <el-row>
          <el-table
            :data="submit.reimburseList"
            stripe
          >
            <el-table-column
              label="报销人"
              prop="applicant"
              align="center"
              width="180px"
            />
            <el-table-column
              label="报销日期"
              prop="applicationTime"
              align="center"
              width="180px"
            />
            <el-table-column
              label="报销金额（元）"
              prop="reimbursementPrice"
              align="center"
              width="250px"
            />
            <el-table-column
              label="操作"
              align="center"
            >
              <template #default="scope">
                <el-button
                  text
                  type="primary"
                  :icon="Edit"
                  @click="openReimburseEdit(scope.row)"
                >
                  编辑
                </el-button>
                <el-button
                  text
                  type="primary"
                  :icon="Delete"
                  @click="reimburseDelete(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
        <el-row justify="end">
          <el-pagination
            v-model:current-page="condition.pageInfo.page"
            background
            layout="prev, pager, next"
            :page-size="8"
            :total="submit.reimburseTotal"
            @change="changeReimbursePage"
          />
        </el-row>
      </el-col>
    </el-row>
    <el-drawer
      v-model="reimburseAddShow"
      title="新增报销记录"
      size="40%"
    >
      <el-form
        label-position="left"
        label-width="100"
        class="mt-5"
      >
        <el-form-item
          label="申请人："
        >
          <el-input
            v-model="createData.applicant"
            placeholder="请输入申请人名称"
            clearable
            @clear="createData.applicant = ''"
          />
        </el-form-item>
        <el-form-item
          label="报销日期："
        >
          <el-date-picker
            v-model="createData.applicationTime"
            placeholder="请选择报销日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            clearable
            @clear="createData.applicationTime = ''"
          />
        </el-form-item>
        <el-form-item
          label="审批人："
        >
          <el-select
            v-model="createData.approval"
            filterable
            placeholder="请选择审批人"
            clearable
            @clear="createData.approval = ''"
          >
            <el-option
              v-for="item in userList"
              :key="item.ID"
              :label="item.nickName"
              :value="item.ID"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="费用类型："
        >
          <el-select
            v-model="createData.genre"
            filterable
            placeholder="请选择费用类型"
            clearable
            @clear="createData.genre = ''"
          >
            <el-option
              v-for="item in costList"
              :key="item.ID"
              :label="item.name"
              :value="item.ID"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="报销总金额：">
          <el-text size="large">{{ totality }}</el-text>
        </el-form-item>
        <el-row
          v-for="(item,index) in createData.feeDetails"
          :key="index"
        >
          <el-col :span="12">
            <el-form-item
              label="报销金额："
            >
              <el-input-number
                v-model="item.feePrice"
                placeholder="请输入报销金额"
                clearable
                size="large"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="报销备注："
            >
              <el-input
                v-model="item.remarks"
                placeholder="请输入报销备注"
                type="textarea"
                maxlength="150"
                show-word-limit
                clearable
                size="large"
                @clear="item.remarks = ''"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-show="createData.feeDetails.length > 1"
            size="large"
            @click="createData.feeDetails.splice(createData.feeDetails.length - 1,1)"
          >
            删除报销详情
          </el-button>
          <el-button
            size="large"
            @click="addFeeDetails"
          >
            添加报销详情
          </el-button>
          <el-button
            type="primary"
            size="large"
            @click="addReimburse"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-drawer>
    <el-drawer
      v-model="reimburseEditShow"
      title="编辑报销记录"
      size="40%"
    >
      <el-form
        label-position="left"
        label-width="100"
        class="mt-5"
      >
        <el-form-item
          label="申请人："
        >
          <el-input
            v-model="editData.applicant"
            placeholder="请输入申请人名称"
            clearable
            @clear="editData.applicant = ''"
          />
        </el-form-item>
        <el-form-item
          label="报销日期："
        >
          <el-date-picker
            v-model="editData.applicationTime"
            placeholder="请选择报销日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            clearable
            @clear="editData.applicationTime = ''"
          />
        </el-form-item>
        <el-form-item
          label="审批人："
        >
          <el-select
            v-model="editData.approval"
            filterable
            placeholder="请选择审批人"
            clearable
            @clear="editData.approval = ''"
          >
            <el-option
              v-for="item in userList"
              :key="item.ID"
              :label="item.nickName"
              :value="item.ID"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="费用类型："
        >
          <el-select
            v-model="editData.genre"
            filterable
            placeholder="请选择费用类型"
            clearable
            @clear="editData.genre = ''"
          >
            <el-option
              v-for="item in costList"
              :key="item.ID"
              :label="item.name"
              :value="item.ID"
            />
          </el-select>
        </el-form-item>
        <el-row>
          <el-col :span="10">
            <el-form-item label="报销总金额：">
              <el-text size="large">{{ editTotality }}</el-text>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row
          v-for="(item,index) in editData.feeDetails"
          :key="index"
        >
          <el-col :span="12">
            <el-form-item
              label="报销金额："
            >
              <el-input-number
                v-model="item.feePrice"
                placeholder="请输入报销金额"
                clearable
                size="large"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="报销备注："
            >
              <el-input
                v-model="item.remarks"
                placeholder="请输入报销备注"
                type="textarea"
                maxlength="150"
                show-word-limit
                clearable
                size="large"
                @clear="item.remarks = ''"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-show="deleteDetailShow"
            size="large"
            @click="delFeeDetails"
          >
            删除报销详情
          </el-button>
          <el-button
            size="large"
            @click="addEditFeeDetails"
          >
            添加报销详情
          </el-button>
          <el-button
            type="primary"
            size="large"
            @click="editReimburse"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { Search, Delete, Edit, Plus } from '@element-plus/icons-vue'
import { reactive, ref, onMounted, computed, defineExpose } from 'vue'
import { reimburseOperate } from '@/pinia/reimbursement/Reimbursement'
import { codeOperate } from '@/pinia/code/code'
import { queryExpensesGenre } from '@/api/finance'
import { getAllUsers } from '@/api/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { createReimburse, deleteReimburse, updateReimburse } from '@/api/reimbursement'
defineOptions({
  name: 'Reimburse'
})
// pinia
const submit = reimburseOperate()
const serial = codeOperate()
// 数据
const reimburseAddShow = ref(false)
const condition = reactive({
  pageInfo: {
    page: 1,
    pageSize: 8
  },
  code: '',
  name: '',
  time: ''
})
const createData = reactive({
  projectCode: '',
  applicant: '',
  applicationTime: '',
  approval: '',
  reimbursementPrice: 0,
  genre: '',
  feeDetails: [{
    remarks: '',
    feePrice: 0
  }]
})
const editData = reactive({})
const reimburseEditShow = ref(false)
const costList = reactive([])
const userList = reactive([])

// 计算属性
const deleteDetailShow = computed(() => {
  for (const i in editData) {
    if (i === 'feeDetails' && editData[i].length > 1) {
      return true
    }
  }
  return false
})
const totality = computed(() => {
  let middle = 0
  createData.feeDetails.forEach(item => {
    middle += item.feePrice
  })
  return middle
})
const editTotality = computed(() => {
  let middle = 0
  editData.feeDetails.forEach(item => {
    middle += parseFloat(item.feePrice)
  })
  return middle
})
// const overall = ref(0)
// 方法
onMounted(() => {
  queryExpensesGenre().then(res => {
    if (res.code === 0) {
      costList.push(...res.data)
    }
  })
  getAllUsers().then(res => {
    if (res.code === 0) {
      userList.length = 0
      userList.push(...res.data)
    }
  })
})
const searchReimburse = () => {
  condition.code = serial.currentCode
  condition.pageInfo.page = 1
  submit.getReimburseList(condition)
}
const openReimburseEdit = (row) => {
  reimburseEditShow.value = true
  Object.assign(editData, row)
}
const reimburseDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该报销记录吗?',
    '删除记录',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      const id = { id: row.ID }
      deleteReimburse(id).then(res => {
        if (res.code === 0) {
          ElMessage({
            message: '删除成功',
            type: 'success',
            showClose: true,
            duration: 2000
          })
          refreshList()
        }
      })
    }).catch(() => {})
}
const changeReimbursePage = (value) => {
  condition.pageInfo.page = value
  submit.getReimburseList(condition)
}
const addReimburse = () => {
  // // 报销总金额
  createData.reimbursementPrice = totality.value
  createData.projectCode = serial.currentCode
  for (const i in createData) {
    if (createData[i] === '' || createData[i] === 0) {
      ElMessage({
        message: '请将信息填写完整',
        type: 'error',
        showClose: true,
        duration: 3000
      })
      return
    }
  }
  createReimburse(createData).then(res => {
    if (res.code === 0) {
      ElMessage({
        message: '添加成功',
        type: 'success',
        showClose: true,
        duration: 2000
      })
      const reset = {
        projectCode: '',
        applicant: '',
        applicationTime: '',
        approval: '',
        genre: '',
        feeDetails: [{
          remarks: '',
          feePrice: 0
        }]
      }
      Object.assign(createData, reset)
      createData.reimbursementPrice = totality.value
      reimburseAddShow.value = false
      refreshList()
    }
  })
}

const editReimburse = () => {
  const editCondition = {
    projectCode: serial.currentCode,
    id: editData.ID,
    applicant: editData.applicant,
    applicationTime: editData.applicationTime,
    approval: editData.approval,
    reimbursementPrice: editTotality.value,
    genre: editData.genre,
    feeDetails: editData.feeDetails
  }
  updateReimburse(editCondition).then(res => {
    if (res.code === 0) {
      ElMessage({
        message: '编辑成功',
        type: 'success',
        showClose: true,
        duration: 2000
      })
      reimburseEditShow.value = false
      refreshList()
    }
  })
}

const refreshList = () => {
  const refresh = condition
  refresh.code = serial.currentCode
  submit.getReimburseList(refresh)
}
const addFeeDetails = () => {
  createData.feeDetails.push({
    remarks: '',
    feePrice: 0
  })
}

const addEditFeeDetails = () => {
  editData.feeDetails.push({
    remarks: '',
    feePrice: 0
  })
}
const delFeeDetails = () => {
  editData.feeDetails.splice(editData.feeDetails.length - 1, 1)
}

const outsideChangePage = () => {
  condition.pageInfo.page = 1
}

const changeReimburseAddShow = () => {
  reimburseAddShow.value = true
}

defineExpose({
  outsideChangePage
})
</script>

<style scoped>

</style>
