<!--
 * @Description: 考核指标管理列表页面
 * @Author: 李亚光
 * @Date: 2023-09-14
 -->
<script lang="ts" setup name="RuleProxyList">
import { reactive, ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { delBatchProxy, delProxy, exportProxy, getListPage, uploadProxy } from '@/api/home/rule/proxy'
import { getDictByCode } from '@/api/system/dict'
import { exportFile } from '@/utils/exportUtils'
import { downloadImg } from '@/utils/download'
const { proxy } = getCurrentInstance() as any
const listQuery = reactive({
  assDept: '', // 责任考核单位
  priIndicators: '', // 一级考核指标
  quotaNo: '', // 指标编码
  quotaProject: '', // 指标项目
  quotaType: '', // 指标类型
  offset: 1,
  limit: 20,
})
const columns = ref([
  {
    text: '考核指标编号',
    value: 'quotaNo',
    align: 'center',
  },
  {
    text: '考核指标项目',
    value: 'quotaProjectName',
    align: 'center',
  },
  {
    text: '考核指标类型',
    value: 'quotaTypeName',
    align: 'center',
  },
  {
    text: '一级考核指标',
    value: 'priIndicators',
    align: 'center',
  },
  {
    text: '指标数据来源',
    value: 'dataSourceName',
    align: 'center',
  },
  {
    text: '指标责任考核单位',
    value: 'assDeptName',
    align: 'center',
  },
  {
    text: '指标计算规则',
    value: 'ruleDesc',
    align: 'center',
  },
  {
    text: '考核分值',
    value: 'score',
    align: 'center',
  },
  {
    text: '备注',
    value: 'remarks',
    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
    total.value = parseInt(response.data.total)
    listLoading.value = false
  })
}
fetchData()
// 查询数据
const search = () => {
  fetchData(false)
}
// 重置
const reset = () => {
  listQuery.assDept = ''
  listQuery.priIndicators = ''
  listQuery.quotaNo = ''
  listQuery.quotaProject = ''
  listQuery.quotaType = ''
  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: `/proxylist/${type}`,
    query: {
      row: JSON.stringify(row),
      id: row.id,
    },
  })
}
// 删除
const delHandler = (row: any) => {
  ElMessageBox.confirm(
    `确定删除${row.quotaNo}吗？一经删除，不可恢复！`,
    '确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    delBatchProxy({ ids: [row.id] }).then((res) => {
      ElMessage.success('操作成功')
      search()
    })
  })
}
// 指标项目下拉列表
const projectList = ref<{ id: string; value: string; name: string }[]>()
// 指标类型下拉列表
const typeList = ref<{ id: string; value: string; name: string }[]>()
// 获取字典
const fetchSelectList = () => {
  getDictByCode('quota_project').then((res) => {
    projectList.value = res.data
  })
  getDictByCode('quota_type').then((res) => {
    typeList.value = res.data
  })
}
fetchSelectList()
// 导出列表
const exportList = () => {
  if (list.value.length) {
    const loading = ElLoading.service({
      lock: true,
      text: 'Loading',
      background: 'rgba(255, 255, 255, 0.8)',
    })
    const data = {
      ...listQuery,
      offset: undefined,
      limit: undefined,
      // ids: selectList.value.map(item => item.id),
    }
    exportProxy(data).then((res) => {
      exportFile(res.data, '考核指标')
      loading.close()
    })
      .catch((_) => {
        loading.close()
      })
  }
  else {
    ElMessage.warning('无可导出内容')
  }
}
// 下载模板
const template = () => {
  const url = `${import.meta.env.VITE_APP_API_BASEURL}/static/quotaInfo.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])
    uploadProxy(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(() => {
      delBatchProxy({ 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.quotaNo" placeholder="考核指标编号" clearable />
      </search-item>
      <search-item>
        <el-select v-model.trim="listQuery.quotaProject" placeholder="考核指标项目" clearable>
          <el-option v-for="item in projectList" :key="item.id" :label="item.name" :value="item.value" />
        </el-select>
      </search-item>
      <search-item>
        <el-select v-model.trim="listQuery.quotaType" placeholder="考核指标类型" clearable>
          <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.value" />
        </el-select>
      </search-item>
      <search-item>
        <el-input v-model.trim="listQuery.priIndicators" placeholder="一级考核指标" clearable />
      </search-item>
      <search-item>
        <el-input v-model.trim="listQuery.assDept" placeholder="责任考核单位" clearable />
      </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('/proxy/add')" type="primary" @click="handler({}, 'create')">
          新增
        </el-button>
        <el-button v-if="proxy.hasPerm('/proxy/import')" type="primary" @click="importList">
          导入
        </el-button>
        <el-button v-if="proxy.hasPerm('/proxy/template')" type="primary" @click="template">
          下载模板
        </el-button>
        <el-button v-if="proxy.hasPerm('/proxy/export')" type="primary" @click="exportList">
          导出
        </el-button>
        <el-button v-if="proxy.hasPerm('/proxy/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="操作" 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('/proxy/update')" link type="primary" size="small" @click="handler(scope.row, 'update')">
                编辑
              </el-button>
              <el-button v-if="proxy.hasPerm('/proxy/delete')" link type="danger" size="small" @click="delHandler(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
  </app-container>
</template>

