<template>
  <div style="width: 97%">
    <el-row>
      <el-col
        :span="24"
      >
        <el-form
          :inline="true"
          style="margin: 15px 0 0 10px;height: 40px"
        >
          <el-form-item label="时间类型:">
            <el-select
              v-model="timeTypeValue"
              placeholder="请选择日期选择器"
              @change="changeTimeType"
            >
              <el-option
                v-for="item in timeTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="timeTypeValue === 'date'"
            label="日期:"
          >
            <el-date-picker
              v-model="condition.dayTime"
              type="date"
              placeholder="请选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              clearable
              @clear="condition.dayTime = ''"
            />
          </el-form-item>
          <el-form-item
            v-if="timeTypeValue === 'month'"
            label="月份:"
          >
            <el-date-picker
              v-model="condition.monthTime"
              type="month"
              placeholder="请选择月份"
              format="YYYY-MM"
              value-format="YYYY-MM"
              clearable
              @clear="condition.monthTime = ''"
            />
          </el-form-item>
          <el-form-item
            v-if="timeTypeValue === 'year'"
            label="年份:"
          >
            <el-date-picker
              v-model="condition.yearTime"
              type="year"
              placeholder="请选择年份"
              format="YYYY"
              value-format="YYYY"
              clearable
              @clear="condition.yearTime = ''"
            />
          </el-form-item>
          <el-form-item label="项目:">
            <el-select
              v-model="projectSelect"
              placeholder="请选择项目"
              clearable
              @clear="clearProject"
            >
              <el-option
                v-for="item in projectList"
                :key="item.ID"
                :label="item.name"
                :value="item.ID"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="类型:">
            <el-select
              v-model="genreSelect"
              placeholder="请选择类型"
              clearable
              @clear="clearGenre"
            >
              <el-option
                v-for="item in costTypeList"
                :key="item.ID"
                :label="item.name"
                :value="item.ID"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="人员:">
            <el-select
              v-model="peopleSelect"
              placeholder="请选择人员名称"
              clearable
              @clear="clearPeopleSelect"
            >
              <el-option
                v-for="item in userList"
                :key="item.ID"
                :label="item.nickName"
                :value="item.ID"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-dropdown
              split-button
              type="primary"
            >
              操作
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>
                    <el-button
                      type="primary"
                      :icon="Search"
                      @click="consultCostList"
                    >查询</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button
                      type="primary"
                      :icon="Refresh"
                      @click="costListReset"
                    >重置</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button
                      type="primary"
                      :icon="Plus"
                      @click="addDetailRecord"
                    >添加</el-button>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click="costTypePopup = true"
            >费用类型</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row style="margin-top: 15px;">
      <el-table
        :data="costList"
        stripe
        border
      >
        <el-table-column
          label="人员名称"
          align="center"
          prop="user.nickName"
          width="180"
        />
        <el-table-column
          label="费用类型"
          align="center"
          prop="expensesGenre.name"
          width="180"
        />
        <el-table-column
          label="时间"
          align="center"
          prop="feeTime"
          width="180"
        />
        <el-table-column
          label="部门"
          align="center"
          prop="department.name"
          width="180"
        />
        <el-table-column
          label="支入金额(元)"
          align="center"
          prop="depositAmount"
          width="180"
        />
        <el-table-column
          label="支出金额(元)"
          align="center"
          prop="expenditureAmount"
          width="180"
        />
        <el-table-column
          label="当前余额(元)"
          align="center"
          prop="thenBalance"
          width="180"
        />
        <el-table-column
          label="操作"
          align="center"
        >
          <template #default="scope">
            <el-popover
              placement="top"
              :width="300"
              trigger="click"
              :content="scope.row.expenseDetail"
            >
              <template #reference>
                <el-button
                  text
                  type="primary"
                  :icon="Notebook"
                >
                  明细
                </el-button>
              </template>
            </el-popover>
            <el-button
              text
              type="primary"
              size="small"
              :icon="Edit"
              @click="costEdit(scope.row)"
            >编辑</el-button>
            <el-button
              text
              type="primary"
              size="small"
              :icon="Delete"
              @click="costDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row
      v-show="costListTotal > 10"
      justify="end"
    >
      <el-pagination
        v-model:current-page="condition.pageInfo.page"
        background
        layout="prev, pager, next"
        :total="costListTotal"
        @change="changeCostPage"
      />
    </el-row>
    <el-drawer
      v-model="editDrawerShow"
      :title="drawerTitle"
      width="40%"
    >
      <el-form
        label-width="90"
        label-position="left"
        size="large"
      >
        <el-form-item label="人员：">
          <el-select
            v-model="editData.reimburser"
            placeholder="请选择人员名称"
          >
            <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.departmentId"
            disabled
            placeholder="请选择费用类型"
          >
            <el-option
              v-for="item in departmentList"
              :key="item.ID"
              :label="item.name"
              :value="item.ID"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="支入金额：">
          <el-input-number
            v-model="editData.depositAmount"
          />
        </el-form-item>
        <el-form-item label="支出金额：">
          <el-input-number
            v-model="editData.expenditureAmount"
          />
        </el-form-item>
        <el-form-item label="时间：">
          <el-date-picker
            v-model="editData.feeTime"
            type="date"
            placeholder="请选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="费用类型：">
          <el-select
            v-model="editData.genre"
            placeholder="请选择费用类型"
          >
            <el-option
              v-for="item in costTypeList"
              :key="item.ID"
              :label="item.name"
              :value="item.ID"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目：">
          <el-select
            v-model="editData.projectId"
            placeholder="请选择项目"
          >
            <el-option
              v-for="item in projectList"
              :key="item.ID"
              :label="item.name"
              :value="item.ID"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注：">
          <el-input
            v-model="editData.remarks"
            placeholder="请填写费用备注"
          />
        </el-form-item>
        <el-form-item label="费用明细：">
          <el-input
            v-model="editData.expenseDetail"
            type="textarea"
            :rows="8"
            :maxlength="400"
            show-word-limit
            placeholder="请填写费用明细"
          />
        </el-form-item>
        <el-form-item label="余额：">
          <el-input-number
            v-model="editData.thenBalance"
          />
        </el-form-item>
      </el-form>
      <el-row
        style="margin-top: 50px"
        justify="end"
      >
        <el-button
          type="primary"
          size="large"
          @click="changeCostList"
        >确认</el-button>
      </el-row>
    </el-drawer>
    <el-dialog
      v-model="costTypePopup"
      title="费用类型"
      width="40%"
    >
      <el-form>
        <el-form-item
          label="编辑类型："
          size="large"
        >
          <el-input
            v-model="changeCostValue"
            style="width: 550px"
            placeholder="请输入费用类型"
          >
            <template #prepend>
              <el-select
                v-model="costTypeSelect"
                placeholder="请选择类型"
                clearable
                style="width: 140px"
                @clear="clearCostType"
              >
                <el-option
                  v-for="item in costTypeList"
                  :key="item.ID"
                  :label="item.name"
                  :value="item.ID"
                />
              </el-select>
            </template>
            <template #append>
              <el-button @click="deleteCostType">删除</el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="editCostType"
          >
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { Search, Plus, Delete, Refresh, Edit, Notebook } from '@element-plus/icons-vue'
import { ref, reactive, onMounted } from 'vue'
import { getAllUsers } from '@/api/user'
import { createFeeGenre, deleteFeeGenre, queryExpensesGenre, updateFeeGenre } from '@/api/finance'
import { getAllProject } from '@/api/project'
import { queryCostList, updateCost } from '@/api/cost'
import { getDepByStart } from '@/api/department'
import { ElMessage, ElMessageBox } from 'element-plus'
import { deleteCost, createCost } from '@/api/cost'
defineOptions({
  name: 'DetailList'
})
const timeTypeList = reactive([
  { label: '按日期查询', value: 'date' },
  { label: '按月份查询', value: 'month' },
  { label: '按年份查询', value: 'year' }
])
// 列表
const userList = reactive([])
const costTypeList = reactive([])
const projectList = reactive([])
const costList = reactive([])
const costListTotal = ref(0)
const departmentList = reactive([])
// 查询数据
const timeTypeValue = ref('date')
const condition = reactive({
  pageInfo: {
    page: 1,
    pageSize: 10
  },
  reimburser: 0,
  projectId: 0,
  genre: 0,
  dayTime: '',
  monthTime: '',
  yearTime: ''
})
const peopleSelect = ref('')
const genreSelect = ref('')
const projectSelect = ref('')
// 编辑数据
const editDrawerShow = ref(false)
const editData = reactive({
  id: 0,
  reimburser: 0,
  departmentId: 0,
  expenditureAmount: 0,
  depositAmount: 0,
  feeTime: '',
  genre: 0,
  projectId: 0,
  expenseDetail: '',
  remarks: '',
  thenBalance: 0
})

// 抽屉类型、标题
const drawerType = ref('')
const drawerTitle = ref('')

// 费用类型修改
const costTypePopup = ref(false)
const changeCostValue = ref('')
const costTypeSelect = ref('')
const deleteCostType = () => {
  if (costTypeSelect.value === '') {
    ElMessage.error('请选择需要删除的费用类型')
    return
  }
  ElMessageBox.confirm(
    '确定进行删除该费用类型吗?',
    '删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      const deleteId = {
        id: costTypeSelect.value
      }
      deleteFeeGenre(deleteId).then(res => {
        if (res.code === 0) {
          ElMessage.success('删除成功')
          getCostTypeList()
          changeCostValue.value = ''
          costTypeSelect.value = ''
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
const editCostType = () => {
  if (changeCostValue.value === '') {
    ElMessage.error('请输入费用类型')
    return
  }
  if (costTypeSelect.value === '') {
    const createCost = {
      name: changeCostValue.value
    }
    createFeeGenre(createCost).then(res => {
      if (res.code === 0) {
        ElMessage.success('新增类型成功')
        getCostTypeList()
        changeCostValue.value = ''
        costTypeSelect.value = ''
      }
    })
  } else {
    const updateCost = {
      id: costTypeSelect.value,
      name: changeCostValue.value
    }
    updateFeeGenre(updateCost).then(res => {
      if (res.code === 0) {
        ElMessage.success('修改类型成功')
        getCostTypeList()
        changeCostValue.value = ''
        costTypeSelect.value = ''
      }
    })
  }
}
const clearCostType = () => {
  costTypeSelect.value = ''
}
// 方法
onMounted(() => {
  getUserList()
  getCostTypeList()
  queryProjectList()
  queryDepartmentList()
  getCostList(0, 0, 0)
})
const costListReset = () => {
  const initial = {
    pageInfo: {
      page: 1,
      pageSize: 10
    },
    reimburser: 0,
    projectId: 0,
    genre: 0,
    dayTime: '',
    monthTime: '',
    yearTime: ''
  }
  projectSelect.value = ''
  genreSelect.value = ''
  peopleSelect.value = ''
  Object.assign(condition, initial)
  consultCostList()
}
const getUserList = () => {
  getAllUsers().then(res => {
    if (res.code === 0) {
      userList.length = 0
      userList.push(...res.data)
    }
  })
}

const getCostTypeList = () => {
  queryExpensesGenre().then(res => {
    if (res.code === 0) {
      costTypeList.length = 0
      console.log('费用类型列表', res.data)
      costTypeList.push(...res.data)
    }
  })
}

const queryProjectList = () => {
  getAllProject().then(res => {
    if (res.code === 0) {
      projectList.length = 0
      console.log('项目列表', res.data)
      projectList.push(...res.data)
    }
  })
}

const queryDepartmentList = () => {
  getDepByStart().then(res => {
    if (res.code === 0) {
      departmentList.length = 0
      departmentList.push(...res.data)
    }
  })
}

const consultCostList = () => {
  let nameId
  let typeId
  let itemId
  peopleSelect.value === '' ? nameId = 0 : nameId = peopleSelect.value
  genreSelect.value === '' ? typeId = 0 : typeId = genreSelect.value
  projectSelect.value === '' ? itemId = 0 : itemId = projectSelect.value
  getCostList(nameId, typeId, itemId)
}
const getCostList = (nameId, typeID, itemId) => {
  condition.reimburser = nameId
  condition.genre = typeID
  condition.projectId = itemId
  queryCostList(condition).then(res => {
    if (res.code === 0) {
      costList.length = 0
      console.log('费用列表', res.data)
      if (res.data.list !== null) {
        costList.push(...res.data.list)
      }
      costListTotal.value = res.data.total
    }
  })
}
const costEdit = (row) => {
  console.log(row)
  editDrawerShow.value = true
  drawerType.value = 'edit'
  drawerTitle.value = '编辑费用'
  editData.id = row.ID
  editData.reimburser = row.reimburser
  editData.departmentId = row.departmentId
  editData.expenditureAmount = row.expenditureAmount
  editData.depositAmount = row.depositAmount
  editData.feeTime = row.feeTime
  editData.genre = row.genre
  editData.expenseDetail = row.expenseDetail
  editData.remarks = row.remarks
  editData.thenBalance = row.thenBalance
  editData.projectId = row.project.ID
}
const costDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除此费用记录吗?',
    '删除记录',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      const data = {
        id: row.ID
      }
      deleteCost(data).then(res => {
        if (res.code === 0) {
          ElMessage.success('删除成功')
          consultCostList()
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
const addDetailRecord = () => {
  const initialData = {
    id: 0,
    reimburser: userList[0].ID,
    departmentId: departmentList[0].ID,
    expenditureAmount: 0,
    depositAmount: 0,
    feeTime: '',
    genre: costTypeList[0].ID,
    projectId: 0,
    expenseDetail: '',
    remarks: '',
    thenBalance: 0
  }
  Object.assign(editData, initialData)
  editDrawerShow.value = true
  drawerType.value = 'add'
  drawerTitle.value = '新增费用'
}

const clearPeopleSelect = () => {
  peopleSelect.value = ''
  condition.reimburser = 0
}

const clearGenre = () => {
  genreSelect.value = ''
  condition.genre = 0
}

const clearProject = () => {
  projectSelect.value = ''
  condition.projectId = 0
}

const changeTimeType = (value) => {
  if (value === 'year') {
    condition.monthTime = ''
    condition.dayTime = ''
  } else if (value === 'month') {
    condition.yearTime = ''
    condition.dayTime = ''
  } else {
    condition.yearTime = ''
    condition.monthTime = ''
  }
}

const changeCostList = () => {
  for (const item in editData) {
    if (item === 'thenBalance') {
      continue
    }
    if (editData[item] === '' || editData[item] === null) {
      ElMessage({
        message: '请将除余额以外的信息填写完整',
        type: 'error',
        showClose: true,
        duration: 2000
      })
      return
    }
  }
  editData.thenBalance = parseFloat(editData.thenBalance)
  editData.expenditureAmount = parseFloat(editData.expenditureAmount)
  editData.depositAmount = parseFloat(editData.depositAmount)
  if (drawerType.value === 'add') {
    createCost(editData).then(res => {
      if (res.code === 0) {
        ElMessage.success('新增成功')
        editDrawerShow.value = false
        consultCostList()
      }
    })
  } else {
    updateCost(editData).then(res => {
      if (res.code === 0) {
        ElMessage.success('修改成功')
        editDrawerShow.value = false
        consultCostList()
      }
    })
  }
}

const changeCostPage = (val) => {
  condition.pageInfo.page = val
  consultCostList()
}
</script>

<style scoped>

</style>
