<!--
 * @Description: 考核方案管理列表页面
 * @Author: 李亚光
 * @Date: 2023-09-14
 -->
<script lang="ts" setup name="RuleProgrammeList">
import { reactive, ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { delBatchProgramme, delProgramme, getListPage, uploadProgramme } from '@/api/home/rule/programme'
import { getDictByCode } from '@/api/system/dict'
import { downloadImg } from '@/utils/download'
const { proxy } = getCurrentInstance() as any
const listQuery = reactive({
  planName: '', // 方案名称
  isEnable: '', // 是否禁用
  assObject: '', // 考核对象
  offset: 1,
  limit: 20,
})
const columns = ref([
  {
    text: '考核方案名称',
    value: 'planName',
    align: 'center',
  },
  {
    text: '考核对象',
    value: 'assObjectName',
    align: 'center',
  },
  {
    text: '具体考核部门',
    value: 'assDept',
    align: 'center',
  },
  {
    text: '考核周期',
    value: 'cycleName',
    align: 'center',
  },
  {
    text: '是否启用',
    value: 'isEnableName',
    align: 'center',
  },
  {
    text: '考核等级评定',
    value: 'recoRatingName',
    align: 'center',
  },
])
const list = ref([])
const total = ref(0)
const listLoading = ref(true)

// 获取数据
const fetchData = (isNowPage = true) => {
  listLoading.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.offset = 1
  }
  getListPage(listQuery).then((response) => {
    list.value = response.data.rows.map((item: any) => {
      return {
        ...item,
        assDept: item.depts.map((child: any) => child.fullName).join(','),
      }
    })
    total.value = parseInt(response.data.total)
    listLoading.value = false
  })
}
fetchData()
// 查询数据
const search = () => {
  fetchData(false)
}
// 重置
const reset = () => {
  listQuery.planName = ''
  listQuery.isEnable = ''
  listQuery.assObject = ''
  listQuery.offset = 1
  listQuery.limit = 20
  search()
}
// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
const changePage = (val: { size: number; page: number }) => {
  if (val && val.size) {
    listQuery.limit = val.size
  }
  if (val && val.page) {
    listQuery.offset = val.page
  }
  fetchData()
}
const $router = useRouter()
// 新建编辑操作
const handler = (row: any, type: string) => {
  $router.push({
    path: `/programmelist/${type}`,
    query: {
      row: JSON.stringify(row),
      id: row.id,
    },
  })
}
// 删除
const delHandler = (row: any) => {
  ElMessageBox.confirm(
    `确定删除${row.planName}吗？一经删除，不可恢复！`,
    '确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    delBatchProgramme({ ids: [row.id] }).then((res) => {
      ElMessage.success('操作成功')
      search()
    })
  })
}
// 考核对象下拉列表
const objectList = ref<{ id: string; value: string; name: string }[]>()
// 是否禁用下拉列表
const disableList = ref<{ id: string; value: string; name: string }[]>()
// 获取字典
const fetchSelectList = () => {
  getDictByCode('ass_object').then((res) => {
    objectList.value = res.data
  })
  getDictByCode('is_enable').then((res) => {
    disableList.value = res.data
  })
}
fetchSelectList()
// 下载模板
const template = () => {
  const url = `${import.meta.env.VITE_APP_API_BASEURL}/static/plan.xlsx`
  downloadImg(url, '考核方案模板')
}
// 导入
const fileRef = ref()
const importList = () => {
  fileRef.value?.click()
}
const onFileChange = (event: any) => {
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    const loading = ElLoading.service({
      lock: true,
      background: 'rgba(255, 255, 255, 0.8)',
    })
    fd.append('file', event.target.files[0])
    uploadProgramme(fd).then((res) => {
      if (res.code === 200) {
        ElMessage.success('文件上传成功')
        fileRef.value.value = ''
        loading.close()
        search()
      }
      else {
        loading.close()
        fileRef.value.value = ''
      }
    }).catch(() => {
      loading.close()
    })
  }
}
// 表格被选中的行
const selectList = ref<any[]>([])
// 表格多选
const multiSelect = (row: any[]) => {
  selectList.value = row
}
// 批量删除
const BatchProxy = () => {
  if (selectList.value.length) {
    // delBatchProxy()
    ElMessageBox.confirm(
      '确定删除选中数据吗？一经删除，不可恢复！',
      '确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      },
    ).then(() => {
      delBatchProgramme({ ids: selectList.value.map((item: any) => item.id) }).then((res) => {
        ElMessage.success('操作成功')
        selectList.value = []
        search()
      })
    })
  }
  else {
    ElMessage.warning('请先选择需要删除的数据')
  }
}
</script>

<template>
  <app-container>
    <!-- 筛选条件 -->
    <search-area :need-clear="true" @search="search" @clear="reset">
      <search-item>
        <el-input v-model.trim="listQuery.planName" placeholder="考核方案名称" clearable />
      </search-item>
      <search-item>
        <el-select v-model.trim="listQuery.assObject" placeholder="指标考核对象" clearable>
          <el-option v-for="item in objectList" :key="item.id" :label="item.name" :value="item.value" />
        </el-select>
      </search-item>
      <!-- <search-item>
        <el-input v-model.trim="listQuery.groupName" placeholder="具体考核部门" clearable />
      </search-item> -->
      <search-item>
        <el-select v-model.trim="listQuery.isEnable" placeholder="是否启用" clearable>
          <el-option v-for="item in disableList" :key="item.id" :label="item.name" :value="item.value" />
        </el-select>
      </search-item>
    </search-area>
    <table-container>
      <template #btns-right>
        <input ref="fileRef" style="display: none;" type="file" @change="onFileChange">
        <el-button v-if="proxy.hasPerm('/programme/add')" type="primary" @click="handler({}, 'create')">
          新增
        </el-button>
        <el-button v-if="proxy.hasPerm('/programme/import')" type="primary" @click="importList">
          导入
        </el-button>
        <el-button v-if="proxy.hasPerm('/programme/template')" type="primary" @click="template">
          下载模板
        </el-button>
        <el-button v-if="proxy.hasPerm('/programme/delete')" type="primary" @click="BatchProxy">
          删除
        </el-button>
      </template>
      <!-- 普通表格 -->
      <normal-table
        :data="list" :total="total" :columns="columns" :query="listQuery" :list-loading="listLoading"
        :is-showmulti-select="true" :is-multi="true" @change="changePage" @multi-select="multiSelect"
      >
        <template #columns>
          <el-table-column label="考核指标项目" align="center">
            <template #default="scope">
              <div class="container">
                <div v-for="(item, index) in scope.row.quotaInfos" :key="item.id" :class="`${index === 0 ? '' : 'item'}`">
                  {{ item.quotaProjectName }}
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="考核指标类型" align="center">
            <template #default="scope">
              <div class="container">
                <div v-for="(item, index) in scope.row.quotaInfos" :key="item.id" :class="`${index === 0 ? '' : 'item'}`">
                  {{ item.priIndicators }}
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="考核得分规则" align="center">
            <template #default="scope">
              {{ scope.row.ruleDescription }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="140" align="center">
            <template #default="scope">
              <el-button link type="primary" size="small" @click="handler(scope.row, 'detail')">
                详情
              </el-button>
              <el-button v-if="proxy.hasPerm('/programme/update')" link type="primary" size="small" @click="handler(scope.row, 'update')">
                编辑
              </el-button>
              <el-button v-if="proxy.hasPerm('/programme/delete')" link type="danger" size="small" @click="delHandler(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
  </app-container>
</template>

<style lang="scss" scope>
.container {
  // display: flex;
  width: 100%;

  .item {
    float: left;
    border-top: 1px solid #ebeef5;
    text-align: center;
    width: 100%;
  }
}
</style>

