<template>
  <div>
    <el-row>
      <el-col
        :span="24"
      >
        <el-form
          :inline="true"
          style="margin: 5px 0 15px 0;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="costTypeSelect"
              placeholder="请选择费用类型"
              clearable
              @clear="clearCostType"
            >
              <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
              filterable
              @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="consultPayList"
                    >查询</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button
                      type="primary"
                      icon="Refresh"
                      @click="payListReset"
                    >重置</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>
      <el-col :span="23">
        <el-table
          :data="costData.projectCostList"
          stripe
          border
        >
          <el-table-column
            label="人员名称"
            align="center"
            prop="user.nickName"
            width="180"
          />
          <el-table-column
            label="费用类型"
            align="center"
            prop="projectFeeGenre.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-col>
    </el-row>
    <el-row
      v-show="costListTotal > 6"
    >
      <el-col
        :span="23"
        class="flex justify-end"
      >
        <el-pagination
          v-model:current-page="condition.pageInfo.page"
          v-model:page-size="condition.pageInfo.pageSize"
          background
          layout="prev, pager, next"
          :total="costData.costListTotal"
          @change="changeCostPage"
        />
      </el-col>
    </el-row>
    <el-drawer
      v-model="drawerShow"
      :title="drawerTitle"
      width="40%"
    >
      <el-form
        label-width="90"
        label-position="left"
        size="large"
      >
        <el-form-item label="人员：">
          <el-select
            v-model="drawerData.reimburser"
            placeholder="请选择人员名称"
            @change="changePeople"
          >
            <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="drawerData.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="drawerData.depositAmount"
          />
        </el-form-item>
        <el-form-item label="支出金额：">
          <el-input-number
            v-model="drawerData.expenditureAmount"
          />
        </el-form-item>
        <el-form-item label="时间：">
          <el-date-picker
            v-model="drawerData.feeTime"
            type="date"
            placeholder="请选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="费用类型：">
          <el-select
            v-model="drawerData.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="drawerData.projectCode"
            placeholder="请选择项目"
          >
            <el-option
              v-for="item in projectList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注：">
          <el-input
            v-model="drawerData.remarks"
            placeholder="请填写费用备注"
          />
        </el-form-item>
        <el-form-item label="费用明细：">
          <el-input
            v-model="drawerData.expenseDetail"
            type="textarea"
            :rows="8"
            :maxlength="400"
            show-word-limit
            placeholder="请填写费用明细"
          />
        </el-form-item>
        <el-form-item label="余额：">
          <el-input-number
            v-model="drawerData.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="changeTypeValue"
            style="width: 550px"
            placeholder="请输入费用类型"
          >
            <template #prepend>
              <el-select
                v-model="changeTypeSelect"
                placeholder="请选择费用类型"
                clearable
                style="width: 140px"
                @clear="clearTypeSelect"
              >
                <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 { reactive, ref, onMounted, defineExpose } from 'vue'
import { payData } from '@/pinia/cost/cost'
import { getDepByStart } from '@/api/department'
import { projectCostTypeList, delProjectCostType, createProjectCost,
  deleteProjectCost, updateProjectCost, postProjectCostType, putProjectCostType } from '@/api/cost'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAllUsers } from '@/api/user'
import { getAllProject } from '@/api/project'
import { codeOperate } from '@/pinia/code/code'

defineOptions({
  name: 'ProjectCost'
})
onMounted(() => {
  // 查询部门
  queryDepartmentList()
  // 查询项目费用类型
  queryProjectCostType()
  // 查询人员列表
  getUserList()
  // 查询项目列表
  queryProjectList()
})
// 获取当前的项目code
const codeBox = codeOperate()
// 项目费用类型
const costTypeList = reactive([])
const costTypeSelect = ref('')
const costTypePopup = ref(false)
const clearCostType = () => {
  costTypeSelect.value = ''
  condition.genre = 0
}
const changeTypeValue = ref('')
const changeTypeSelect = ref('')
const clearTypeSelect = () => {
  changeTypeSelect.value = ''
}
const deleteCostType = () => {
  if (changeTypeSelect.value === '') {
    ElMessage.error('请选择需要删除的费用类型')
    return
  }
  ElMessageBox.confirm(
    '确定进行删除该费用类型吗?',
    '删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      const deleteId = {
        id: changeTypeSelect.value
      }
      delProjectCostType(deleteId).then(res => {
        if (res.code === 0) {
          ElMessage.success('删除成功')
          queryProjectCostType()
          changeTypeValue.value = ''
          changeTypeSelect.value = ''
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
const queryProjectCostType = () => {
  projectCostTypeList().then(res => {
    if (res.code === 0) {
      costTypeList.length = 0
      costTypeList.push(...res.data)
    }
  })
}
const editCostType = () => {
  if (changeTypeValue.value === '') {
    ElMessage.error('请输入费用类型')
    return
  }
  if (changeTypeSelect.value === '') {
    const createCost = {
      name: changeTypeValue.value
    }
    postProjectCostType(createCost).then(res => {
      if (res.code === 0) {
        ElMessage.success('新增类型成功')
        queryProjectCostType()
        changeTypeValue.value = ''
        changeTypeSelect.value = ''
      }
    })
  } else {
    const updateCost = {
      id: changeTypeSelect.value,
      name: changeTypeValue.value
    }
    putProjectCostType(updateCost).then(res => {
      if (res.code === 0) {
        ElMessage.success('修改类型成功')
        queryProjectCostType()
        changeTypeSelect.value = ''
        changeTypeValue.value = ''
      }
    })
  }
}
// 部门
const departmentList = reactive([])
const queryDepartmentList = () => {
  getDepByStart().then(res => {
    if (res.code === 0) {
      departmentList.length = 0
      departmentList.push(...res.data)
    }
  })
}

// 抽屉新增编辑信息
const drawerTitle = ref('新增项目费用项')
const drawerShow = ref(false)
const drawerData = reactive({
  reimburser: 0,
  departmentId: 0,
  expenditureAmount: 0,
  depositAmount: 0,
  projectCode: '',
  feeTime: '',
  genre: 0,
  expenseDetail: '',
  remarks: '',
  thenBalance: 0,
})
const drawerDataType = ref('add')
const changeCostList = () => {
  for (const i in drawerData) {
    if (drawerData[i] === '' || drawerData[i] === null) {
      ElMessage.error('请将信息填写完整')
      return
    }
  }
  if (drawerDataType.value === 'add') {
    createProjectCost(drawerData).then(res => {
      if (res.code === 0) {
        ElMessage.success('新增成功')
        drawerShow.value = false
        consultPayList()
      }
    })
  } else {
    updateProjectCost(drawerData).then(res => {
      if (res.code === 0) {
        ElMessage.success('编辑成功')
        drawerShow.value = false
        consultPayList()
      }
    })
  }
  // 刷新汇总
  say()
}

// 费用数据存储
const costData = payData()

// 搜索条件
const condition = reactive({
  pageInfo: {
    page: 1,
    pageSize: 8
  },
  reimburser: 0,
  projectCode: '',
  genre: 0,
  dayTime: '',
  monthTime: '',
  yearTime: ''
})

// 时间搜索
const timeTypeList = reactive([
  { label: '按日期查询', value: 'date' },
  { label: '按月份查询', value: 'month' },
  { label: '按年份查询', value: 'year' }
])
const timeTypeValue = ref('date')
const changeTimeType = (value) => {
  if (value === 'year') {
    condition.monthTime = ''
    condition.dayTime = ''
  } else if (value === 'month') {
    condition.yearTime = ''
    condition.dayTime = ''
  } else {
    condition.yearTime = ''
    condition.monthTime = ''
  }
}

// 项目搜索
const projectList = reactive([])
const queryProjectList = () => {
  getAllProject().then(res => {
    if (res.code === 0) {
      projectList.length = 0
      projectList.push(...res.data)
    }
  })
}

// 人员搜索
const peopleSelect = ref('')
const userList = reactive([])
const clearPeopleSelect = () => {
  peopleSelect.value = ''
  condition.reimburser = 0
}
const getUserList = () => {
  getAllUsers().then(res => {
    if (res.code === 0) {
      userList.length = 0
      userList.push(...res.data)
    }
  })
}
const changePeople = (val) => {
  userList.forEach(item => {
    if (val === item.ID) {
      drawerData.departmentId = item.departmentId
    }
  })
}

// 查询费用列表
const consultPayList = () => {
  condition.genre = costTypeSelect.value === '' ? 0 : costTypeSelect.value
  condition.reimburser = peopleSelect.value === '' ? 0 : peopleSelect.value
  condition.projectCode = codeBox.currentCode
  costData.getCostList(condition)
}

// 重置
const payListReset = () => {
  const initialCondition = {
    pageInfo: {
      page: 1,
      pageSize: 8
    },
    reimburser: 0,
    projectCode: '',
    genre: 0,
    dayTime: '',
    monthTime: '',
    yearTime: ''
  }
  Object.assign(condition, initialCondition)
  costTypeSelect.value = ''
  peopleSelect.value = ''
  condition.projectCode = codeBox.currentCode
  costData.getCostList(condition)
}

// 添加项目费用
const addDetailRecord = () => {
  drawerTitle.value = '新增项目费用项'
  drawerDataType.value = 'add'
  const initialData = {
    reimburser: userList[0].ID,
    departmentId: userList[0].departmentId,
    expenditureAmount: 0,
    depositAmount: 0,
    projectCode: codeBox.currentCode,
    feeTime: '',
    genre: costTypeList[0].ID,
    expenseDetail: '',
    remarks: '',
    thenBalance: 0
  }
  Object.assign(drawerData, initialData)
  drawerShow.value = true
}

const costEdit = (val) => {
  drawerTitle.value = '编辑项目费用项'
  drawerDataType.value = 'edit'
  const editData = {
    id: val.ID,
    reimburser: val.reimburser,
    departmentId: val.departmentId,
    expenditureAmount: val.expenditureAmount,
    depositAmount: val.depositAmount,
    projectCode: val.projectCode,
    feeTime: val.feeTime,
    genre: val.genre,
    expenseDetail: val.expenseDetail,
    remarks: val.remarks,
    thenBalance: val.thenBalance
  }
  Object.assign(drawerData, editData)
  drawerShow.value = true
}
// 删除项目费用
const costDelete = (val) => {
  ElMessageBox.confirm(
    '确定进行删除该项目费用吗?',
    '删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      const deleteId = {
        id: val.ID
      }
      deleteProjectCost(deleteId).then(res => {
        if (res.code === 0) {
          ElMessage.success('删除成功')
          consultPayList()
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

// 页码
const costListTotal = ref(8)
const changeCostPage = (val) => {
  condition.pageInfo.page = val
  consultPayList()
}
// 重置页码
const outsideChangePage = () => {
  condition.pageInfo.page = 1
}

defineExpose({
  outsideChangePage
})

// 项目费用改变后刷新项目费用汇总
const emit = defineEmits(['refresh'])

const say = () => {
  emit('refresh')
}
</script>

<style scoped>
</style>
