<template>
  <div class="gva-table-box">
    <el-tabs
      v-model="activeName"
      class="demo-tabs"
    >
      <el-tab-pane
        label="报销"
        name="first"
      >
        <el-header>
          <el-row>
            <el-col :span="20">
              <el-form inline>
                <el-form-item label="名称">
                  <el-input v-model="searchDailyExpenses.name" />
                </el-form-item>
                <el-form-item label="时间">
                  <el-date-picker
                    v-model="searchDailyExpenses.time"
                    type="date"
                    placeholder="选择日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
                <el-form-item label="类型">
                  <el-select
                    v-model.number="searchDailyExpenses.state"
                    placeholder="查询"
                    style="width: 115px"
                    clearable
                    filterable
                  >
                    <el-option
                      v-for="item in feeGenre"
                      :key="item.ID"
                      :label="item.name"
                      :value="item.ID"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button
                    type="primary"
                    @click="queryData"
                  >查询</el-button>
                </el-form-item>
              </el-form>
            </el-col>
            <el-col :span="4">
              <el-button @click="openFeeGenre = true">费用类型</el-button>
              <el-button @click="dailyExpensesOpen">新增记录</el-button>
            </el-col>
          </el-row>
        </el-header>
        <el-main>
          <el-table :data="dailyExpensesTable">
            <el-table-column
              prop="name"
              label="名称"
            >
              <template #default="scope">
                <el-button
                  type="primary"
                  link
                  @click="expensesDetailsData(scope.row)"
                >{{ scope.row.name }}</el-button>
              </template>
            </el-table-column>
            <el-table-column
              prop="expensesGenre.name"
              label="费用类型"
            />
            <el-table-column
              prop="applicant"
              label="申请人"
            />
            <el-table-column
              prop="user.nickName"
              label="负责人"
            />
            <el-table-column
              prop="totalAmount"
              label="报销总金额"
            />
            <el-table-column
              prop="applicationTime"
              label="申请日期"
            />
          </el-table>
          <div class="gva-pagination">
            <el-pagination
              :current-page="searchDailyExpenses.pageInfo.page"
              :page-size="searchDailyExpenses.pageInfo.pageSize"
              :page-sizes="[10, 30, 50, 100]"
              :total="dailyExpensesTotal"
              layout="total, sizes, prev, pager, next, jumper"
              @current-change="dailyExpensesCurrentChange"
              @size-change="dailyExpensesSizeChange"
            />
          </div>
          <!--           新增-->
          <el-drawer
            v-model="openDailyExpenses"
            title="报销记录"
            direction="rtl"
            size="50%"
          >
            <el-form
              label-width="auto"
              style="max-width: 900px"
            >
              <el-form-item label="名称">
                <el-input
                  v-model="dailyExpensesData.name"
                  style="width: 300px"
                />
              </el-form-item>
              <el-form-item label="费用类型">
                <el-select v-model="dailyExpensesData.genre">
                  <el-option
                    v-for="item in feeGenre"
                    :key="item.ID"
                    :label="item.name"
                    :value="item.ID"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="申请人">
                <el-input
                  v-model="dailyExpensesData.applicant"
                  style="width: 300px"
                />
              </el-form-item>
              <el-form-item label="申请时间">
                <el-date-picker
                  v-model="dailyExpensesData.applicationTime"
                  type="date"
                  placeholder="选择日期"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
              <el-form-item label="负责人">
                <el-select v-model="dailyExpensesData.charge">
                  <el-option
                    v-for="item in users"
                    :key="item.ID"
                    :label="item.nickName"
                    :value="item.ID"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="总金额">
                <el-input-number
                  v-model="dailyExpensesData.totalAmount"
                  style="width: 300px"
                  :precision="2"
                  disabled
                />
              </el-form-item>
              <el-form-item>
                <el-table
                  :data="dailyExpensesData.dailyFeeDetails"
                  row-key="id"
                >
                  <el-table-column
                    label="序号"
                    property="id"
                    prop="id"
                  />
                  <el-table-column
                    property="illustrate"
                    label="费用说明"
                  >
                    <template #default="scope">
                      <el-input
                        v-model="scope.row.illustrate"
                        type="textarea"
                        maxlength="100"
                        show-word-limit
                      />
                    </template>
                  </el-table-column>
                  <el-table-column
                    property="price"
                    label="报销金额"
                  >
                    <template #default="scope">
                      <el-input-number
                        v-model.number="scope.row.price"
                        :precision="2"
                        :min="0"
                        @change="sumExpenses"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column
                    property="feeTime"
                    label="日期"
                  >
                    <template #default="scope">
                      <el-date-picker
                        v-model="scope.row.feeTime"
                        type="date"
                        placeholder="选择日期"
                        value-format="YYYY-MM-DD"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="操作"
                  >
                    <template #default="scope">
                      <el-button
                        @click="handleDelete(scope.row.id)"
                      >删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="success"
                  @click="addLineData"
                >添加一行</el-button>
              </el-form-item>
            </el-form>
            <template #footer>
              <div style="flex: auto">
                <el-button
                  type="warning"
                  @click="erasureDailyExpenses"
                >删除</el-button>
                <el-button @click="openDailyExpenses = false">取消</el-button>
                <el-button
                  type="primary"
                  @click="saveDailyExpenses"
                >保存</el-button>
              </div>
            </template>
          </el-drawer>
          <!--          费用类型-->
          <el-dialog
            v-model="openFeeGenre"
            title="费用类型"
            width="800"
            align-center
          >
            <el-collapse v-model="activeNames">
              <el-collapse-item
                title="操作"
                name="1"
              >
                <el-form>
                  <el-form-item label="施工人员">
                    <el-input
                      v-model="feeGenreData.name"
                      style="width: 400px"
                    >
                      <template #prepend>
                        <el-select
                          v-model="feeGenreData.id"
                          placeholder="查询"
                          style="width: 115px"
                          clearable
                          filterable
                        >
                          <el-option
                            v-for="item in feeGenre"
                            :key="item.ID"
                            :label="item.name"
                            :value="item.ID"
                          />
                        </el-select>
                      </template>
                      <template #append>
                        <el-button @click="erasureFeeGenre">删除</el-button>
                      </template>
                    </el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button @click="saveFeeGenre">保存</el-button>
                  </el-form-item>
                </el-form>
              </el-collapse-item>
              <el-collapse-item
                title="列表"
                name="2"
              >
                <div>
                  <el-table :data="feeGenre">
                    <el-table-column
                      prop="ID"
                      label="编号"
                    />
                    <el-table-column
                      prop="name"
                      label="姓名"
                    />
                  </el-table>
                </div>
              </el-collapse-item>
            </el-collapse>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="openFeeGenre = false">取消</el-button>
                <el-button
                  type="primary"
                  @click="openFeeGenre = false"
                >
                  确定
                </el-button>
              </div>
            </template>
          </el-dialog>
        </el-main>
      </el-tab-pane>
      <el-tab-pane
        label="支借"
        name="second"
      >
        <el-header>
          <el-row>
            <el-col :span="20">
              <el-form inline>
                <el-form-item label="名称">
                  <el-input v-model="searchBorrowing.name" />
                </el-form-item>
                <el-form-item label="时间">
                  <el-date-picker
                    v-model="searchBorrowing.time"
                    type="date"
                    placeholder="选择日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button
                    type="primary"
                    @click="queryData"
                  >查询</el-button>
                </el-form-item>
              </el-form>
            </el-col>
            <el-col :span="4">
              <el-button @click="addBorrowing">新增数据</el-button>
            </el-col>
          </el-row>
        </el-header>
        <el-main>
          <el-table :data="borrowingTable">
            <el-table-column
              prop="name"
              label="名称"
            >
              <template #default="scope">
                <el-button
                  type="primary"
                  link
                  @click="openBorrowing(scope.row)"
                >{{ scope.row.name }}</el-button>
              </template>
            </el-table-column>
            <el-table-column
              prop="applicant"
              label="申请人"
            />
            <el-table-column
              prop="user.nickName"
              label="负责人"
            />
            <el-table-column
              prop="price"
              label="支借金额"
            />
            <el-table-column
              prop="applicationTime"
              label="申请日期"
            />
          </el-table>
          <div class="gva-pagination">
            <el-pagination
              :current-page="searchBorrowing.pageInfo.page"
              :page-size="searchBorrowing.pageInfo.pageSize"
              :page-sizes="[10, 30, 50, 100]"
              :total="borrowingTotal"
              layout="total, sizes, prev, pager, next, jumper"
              @current-change="borrowingCurrentChange"
              @size-change="borrowingSizeChange"
            />
          </div>
          <el-dialog
            v-model="borrowingDialog"
            title="详情"
            width="500"
            align-center
          >
            <div>
              <el-form
                label-width="auto"
                style="max-width: 400px"
              >
                <el-form-item label="名称">
                  <el-input v-model="borrowingData.name" />
                </el-form-item>
                <el-form-item label="申请人">
                  <el-input v-model="borrowingData.applicant" />
                </el-form-item>
                <el-form-item label="申请日期">
                  <el-date-picker
                    v-model="borrowingData.applicationTime"
                    type="date"
                    placeholder="选择日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
                <el-form-item label="负责人">
                  <el-select v-model="borrowingData.charge">
                    <el-option
                      v-for="item in users"
                      :key="item.ID"
                      :label="item.nickName"
                      :value="item.ID"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="支借金额">
                  <el-input-number
                    v-model="borrowingData.price"
                    :min="0.00"
                    :precision="2"
                  />
                </el-form-item>
              </el-form>
            </div>
            <template #footer>
              <div class="dialog-footer">
                <el-button
                  type="warning"
                  @click="erasureBorrowing"
                >删除</el-button>
                <el-button @click="borrowingDialog = false">取消</el-button>
                <el-button
                  type="primary"
                  @click="saveBorrowing"
                >
                  保存
                </el-button>
              </div>
            </template>
          </el-dialog>
        </el-main>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  createBorrowing, createConstructor,
  createDailyExpenses, createFeeGenre, deleteBorrowing, deleteConstructor,
  deleteDailyExpenses, deleteFeeGenre, queryBorrowingList,
  queryDailyExpensesList,
  queryExpensesGenre, updateBorrowing, updateConstructor,
  updateDailyExpenses, updateFeeGenre
} from '@/api/finance'
import { getAllUsers } from '@/api/user'

// 数据初始化
const feeGenre = ref()
const users = ref()

const dailyExpensesTable = ref()
const dailyExpensesTotal = ref(0)
const searchDailyExpenses = ref({
  pageInfo: {
    page: 1,
    pageSize: 10
  },
  name: '',
  time: '',
  state: null
})
// 分页
const dailyExpensesSizeChange = (val) => {
  searchDailyExpenses.value.pageInfo.pageSize = val
  queryData()
}

const dailyExpensesCurrentChange = (val) => {
  searchDailyExpenses.value.pageInfo.page = val
  queryData()
}

const borrowingTable = ref()
const borrowingTotal = ref(0)
const searchBorrowing = ref({
  pageInfo: {
    page: 1,
    pageSize: 10
  },
  name: '',
  time: ''
})
// 分页
const borrowingSizeChange = (val) => {
  searchBorrowing.value.pageInfo.pageSize = val
  queryData()
}

const borrowingCurrentChange = (val) => {
  searchBorrowing.value.pageInfo.page = val
  queryData()
}

const queryData = async() => {
  if (searchDailyExpenses.value.state === '') {
    searchDailyExpenses.value.state = null
  }
  await queryExpensesGenre().then(res => {
    console.log(res.data)
    feeGenre.value = res.data
  })
  await getAllUsers().then(res => {
    users.value = res.data
  })
  await queryDailyExpensesList(searchDailyExpenses.value).then(res => {
    dailyExpensesTable.value = res.data.list
    searchDailyExpenses.value.pageInfo.page = res.data.page
    searchDailyExpenses.value.pageInfo.pageSize = res.data.pageSize
    dailyExpensesTotal.value = res.data.total
  })
  await queryBorrowingList(searchBorrowing.value).then(res => {
    console.log(res)
    borrowingTable.value = res.data.list
    searchBorrowing.value.pageInfo.page = res.data.page
    searchBorrowing.value.pageInfo.pageSize = res.data.pageSize
    borrowingTotal.value = res.data.total
  })
}

const activeName = ref('first')

// 日常报销
const openDailyExpenses = ref(false)

const dailyExpensesOpen = () => {
  dailyExpensesData.value = {
    name: '',
    genre: null,
    applicant: '',
    applicationTime: '',
    charge: null,
    totalAmount: 0,
    dailyFeeDetails: [{
      id: 1,
      feeTime: '',
      illustrate: '',
      price: 0
    }]
  }
  openDailyExpenses.value = true
}

const dailyExpensesData = ref({
  name: '',
  genre: null,
  applicant: '',
  applicationTime: '',
  charge: null,
  totalAmount: 0,
  dailyFeeDetails: [{
    id: 1,
    feeTime: '',
    illustrate: '',
    price: 0
  }]
})

const addLineData = () => {
  const newData = {
    id: dailyExpensesData.value.dailyFeeDetails.length + 1,
    feeTime: '',
    illustrate: '',
    price: 0
  }
  dailyExpensesData.value.dailyFeeDetails.push(newData)
}

const handleDelete = (val) => {
  ElMessageBox.confirm('确认删除该条数据？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const ds = dailyExpensesData.value.dailyFeeDetails.filter(item => item.id !== val)
    for (let i = 0; i < ds.length; i++) {
      ds[i].id = i + 1
    }
    dailyExpensesData.value.dailyFeeDetails = ds
  })
}

const sumExpenses = () => {
  let sum = 0
  for (const key in dailyExpensesData.value.dailyFeeDetails) {
    sum += dailyExpensesData.value.dailyFeeDetails[key].price
  }
  dailyExpensesData.value.totalAmount = sum
}

// 保存
const saveDailyExpenses = async() => {
  for (let i = 0; i < dailyExpensesData.value.dailyFeeDetails.length; i++) {
    dailyExpensesData.value.dailyFeeDetails[i].id = null
  }
  const dd = dailyExpensesData.value
  // 校验
  if (dd.name === '' || dd.genre == null || dd.charge == null || dd.applicationTime === '' || dd.applicant === '') {
    ElMessage.error('请将数据填写完整')
    return false
  }
  if (dd.ID === null) {
    await createDailyExpenses(dd).then(res => {
      if (res.code === 0) {
        ElMessage.success('新增成功')
        queryData()
        openDailyExpenses.value = false
      }
    })
  } else {
    await updateDailyExpenses(dd).then(res => {
      if (res.code === 0) {
        ElMessage.success('修改成功')
        queryData()
        openDailyExpenses.value = false
      }
    })
  }
}

// 详情
const expensesDetailsData = (val) => {
  console.log(val)
  dailyExpensesData.value = val
  openDailyExpenses.value = true
}

// 删除
const erasureDailyExpenses = async() => {
  for (let i = 0; i < dailyExpensesData.value.dailyFeeDetails.length; i++) {
    dailyExpensesData.value.dailyFeeDetails[i].id = null
  }
  const dd = dailyExpensesData.value
  ElMessageBox.confirm(
    '确定进行删除操作吗?',
    '删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      await deleteDailyExpenses(dd).then(res => {
        console.log(res)
        if (res.code === 0) {
          ElMessage.success('删除成功')
          queryData()
          openDailyExpenses.value = false
        }
      })
    })
}

// 支借
const borrowingDialog = ref(false)

const borrowingData = ref({
  ID: null,
  name: '',
  applicant: '',
  applicationTime: '',
  charge: null,
  price: 0
})

const openBorrowing = (val) => {
  borrowingData.value = val
  borrowingDialog.value = true
}

const addBorrowing = () => {
  borrowingData.value = {
    ID: null,
    name: '',
    applicant: '',
    applicationTime: '',
    charge: null,
    price: 0
  }
  borrowingDialog.value = true
}

// 保存
const saveBorrowing = async() => {
  const dd = borrowingData.value
  // 校验
  if (dd.name === '' || dd.charge == null || dd.applicationTime === '' || dd.applicant === '') {
    ElMessage.error('请将数据填写完整')
    return false
  }
  if (dd.ID === null) {
    await createBorrowing(dd).then(res => {
      if (res.code === 0) {
        ElMessage.success('新增成功')
        queryData()
        borrowingDialog.value = false
      }
    })
  } else {
    await updateBorrowing(dd).then(res => {
      if (res.code === 0) {
        ElMessage.success('修改成功')
        queryData()
        borrowingDialog.value = false
      }
    })
  }
}

// 删除
const erasureBorrowing = async() => {
  const dd = borrowingData.value
  console.log(borrowingData.value)
  ElMessageBox.confirm(
    '确定进行删除操作吗?',
    '删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      await deleteBorrowing(dd).then(res => {
        console.log(res)
        if (res.code === 0) {
          ElMessage.success('删除成功')
          queryData()
          borrowingDialog.value = false
        }
      })
    })
}

// 费用类型
const activeNames = ref(['1'])
const openFeeGenre = ref(false)

const feeGenreData = ref({
  id: null,
  name: ''
})

const saveFeeGenre = async() => {
  if (feeGenreData.value.name === '') {
    ElMessage.error('数据不能为空')
    return false
  }
  if (feeGenreData.value.id === null ) {
    await createFeeGenre(feeGenreData.value).then(res => {
      if (res.code === 0) {
        ElMessage.success('新增成功')
      }
      queryData()
    })
  } else {
    await updateFeeGenre(feeGenreData.value).then(res => {
      if (res.code === 0) {
        ElMessage.success('修改成功')
      }
      queryData()
    })
  }
}

// 删除
const erasureFeeGenre = async() => {
  if (feeGenreData.value.id === null) {
    ElMessage.error('请选择人员')
    return false
  }
  ElMessageBox.confirm(
    '确定进行删除操作吗?',
    '删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      await deleteFeeGenre(feeGenreData.value).then(res => {
        if (res.code === 0) {
          ElMessage.success('删除成功')
        }
        queryData()
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

onMounted(() => {
  queryData()
})
</script>

<style scoped lang="scss">

</style>
