<script setup lang="ts">
import { ref, getCurrentInstance, reactive } from "vue";
import { useRouter } from "vue-router";
import request, { download } from '~/utils/request';
import { pick } from 'lodash-es';
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import type { AxiosRequestConfig } from 'axios'

// #region (constant)
const TABLE_KEY = 'cs_id'
const URL_CUT = '/common/sjzd'
const URL_CUT_REF = ref(URL_CUT)
const URL_SUBMIT_KEY = URL_CUT.split('/').join('_').slice(1)
const instance = getCurrentInstance()
const router = useRouter()
// #endregion

// #region (variable)
const loading_table = ref(true)
let whichDialogSubmit: 'add' | 'edit'
// #endregion

// #region (type)
type TYPE_TABLE_FIELD = {
  [TABLE_KEY]: string;
  'cs_pid': string; // 上级编号
  'cs_name': string; // 字典名称
  'cs_code': string; // 字典编号
  'cs_sort': string; // 排序编号
  'cs_level': string; // 字典层级(备用)
  'cs_path': string; // 字典路径(备用)
  'cs_zdlx': string; // 字典类型
  'cs_sfqy': string; // 是否启用
  'cs_sjlx': string; // 数据类型
  'cs_sjcd': string; // 数据长度
  'cs_bz': string; // 备注
  'cs_pcode': string; // 父级code
}
// #endregion

// #region (props)
// #endregion

// #region (query row)
const queryForm_Data = ref<Partial<TYPE_TABLE_FIELD> & { keyword?: string }>({})

const handleQueryFormBtn_search = () => {
  queryApi()
}
const handleQueryFormBtn_clear = () => {
  queryForm_Data.value = {}
}
// #endregion

// #region (table selection)
const multipleSelection = ref<TYPE_TABLE_FIELD[]>([])
const handleSelectionChange = (val: TYPE_TABLE_FIELD[]) => {
  multipleSelection.value = val
}
// #endregion

// #region (table row)
const handleTableRowBtn_import = async ({ file }: { file: File }) => {
  const res = await API_MAP['import']({ file })
  if (res.code === '1') {
    queryApi()
    ElMessage.success(res.msg)
  }
}
const handleTableRowBtn_export = () => {
  if (multipleSelection.value.length === 0) return ElMessage.info('请先勾选导出文件'); exportApi({ [TABLE_KEY]: multipleSelection.value.map((item: TYPE_TABLE_FIELD) => item[TABLE_KEY])?.join() })
}
const handleTableRowBtn_add = () => {
  whichDialogSubmit = 'add'
  dialogForm_Data.value = {}
  dialogForm_Data.value.cs_pcode = 'BXLB'
  dialogVisible_addOrEdit.value = true
}
const handleTableRowBtn_delete = async () => {
  if (multipleSelection.value.length === 0) return ElMessage.info('请先勾选文件'); const resp = await deleteApi(multipleSelection.value.map((item: TYPE_TABLE_FIELD) => item[TABLE_KEY])); if (resp.code !== '1') return; ElMessage.success('删除成功');
  queryApi()
}
// #endregion

// #region (table body)
const tableData = ref<TYPE_TABLE_FIELD[]>([])

const handleTableColBtn_edit = async (scope: { row: TYPE_TABLE_FIELD }) => {
  whichDialogSubmit = 'edit'
  const res = await detailApi(scope.row[TABLE_KEY])
  dialogForm_Data.value = (res.data?.one_info)
  dialogVisible_addOrEdit.value = true
}
const handleTableColBtn_delete = async (scope: { row: TYPE_TABLE_FIELD }) => {
  const resp = await deleteApi(scope.row[TABLE_KEY]); if (resp.code !== '1') return; ElMessage.success('删除成功');
  queryApi()
}
// #endregion

// #region (pagination)
const total = ref(0)
const limit = ref(10)

const currentPage = ref(1)
function handleCurrentChange() {
  queryApi()
}
// #endregion

// #region (dialog base)
const dialogForm_Data = ref<Partial<TYPE_TABLE_FIELD> & { keyword?: string }>({})

const handleDialogFormBtn_submit = async (formRefKey: string, extendData?: Partial<TYPE_TABLE_FIELD>) => {
  const isValid = await (instance?.refs[formRefKey] as FormInstance).validate((valid: boolean) => valid)
  if (isValid) {
    const resp = await API_MAP[whichDialogSubmit](<TYPE_TABLE_FIELD>({ ...dialogForm_Data.value, ...extendData, cs_pid: '837' }))
    if (resp.code !== '1') return; ElMessage.success('操作成功'); handleDialogFormBtn_cancel()
    queryApi()
  }
}
const handleDialogFormBtn_cancel = (formRefKey?: string) => {
  dialogVisible_addOrEdit.value = false
}
// #endregion

// #region (dialog add/edit)
const dialogVisible_addOrEdit = ref<boolean>(false)

const dialogForm_Ref_addOrEdit = ref<FormInstance>()
const dialogForm_Rules_addOrEdit = reactive({
  'cs_pid': { required: true, message: '上级编号不能为空', trigger: 'submit' },
  'cs_name': { required: true, message: '报修类别名称不能为空', trigger: 'submit' },
  'cs_code': { required: true, message: '字典编号不能为空', trigger: 'submit' },
  'cs_sort': { required: true, message: '排序编号不能为空', trigger: 'submit' },
  'cs_level': { required: true, message: '字典层级(备用)不能为空', trigger: 'submit' },
  'cs_path': { required: true, message: '字典路径(备用)不能为空', trigger: 'submit' },
  'cs_zdlx': { required: true, message: '字典类型不能为空', trigger: 'submit' },
  'cs_sfqy': { required: true, message: '是否启用不能为空', trigger: 'submit' },
  'cs_sjlx': { required: true, message: '数据类型不能为空', trigger: 'submit' },
  'cs_sjcd': { required: true, message: '数据长度不能为空', trigger: 'submit' },
  'cs_bz': { required: true, message: '备注不能为空', trigger: 'submit' },
  'cs_pcode': { required: true, message: '父级code不能为空', trigger: 'submit' },
})
// #endregion

// #region (request api):
function queryApi() {
  loading_table.value = true
  return request({
    url: URL_CUT + '/index',
    data: {
      ...queryForm_Data.value,
      limit: limit.value,
      page: currentPage.value,
      cs_pid: 837,
      sort_field: 'cs_id',
      sort_type: 'DESC',
    }
  }).then((response: { data: { total_rows: string, page_data: TYPE_TABLE_FIELD[] } }) => {
    const { data } = response
    total.value = parseInt(data.total_rows)
    tableData.value = data.page_data
    return response
  }).then(() => {
    loading_table.value = false
  })
}

function addApi(data: TYPE_TABLE_FIELD) {
  return request({
    url: URL_CUT + '/add',
    data: {
      [URL_SUBMIT_KEY]: data,
    }
  })
}

function editApi(data: Partial<TYPE_TABLE_FIELD>) {
  return request({
    url: URL_CUT + '/edit',
    data: {
      [TABLE_KEY]: data[TABLE_KEY],
      [URL_SUBMIT_KEY]: pick(data, ['cs_pid', 'cs_name', 'cs_code', 'cs_sort', 'cs_level', 'cs_path', 'cs_zdlx', 'cs_sfqy', 'cs_sjlx', 'cs_sjcd', 'cs_bz', 'cs_pcode',]),
    }
  })
}

function deleteApi(id: string | string[]) {
  return request({
    url: URL_CUT + '/delete',
    data: {
      [TABLE_KEY]: id,
    }
  })
}

function detailApi(id: string) {
  return request({
    url: URL_CUT + '/detail',
    data: {
      [TABLE_KEY]: id,
    }
  })
}

function importApi(data: { file: File }) {
  return request({
    $type: 'import',
    url: URL_CUT + '/import',
    data
  } as AxiosRequestConfig)
}

function exportApi(d) {
  return download(URL_CUT + '/index', { ...queryForm_Data.value, ...d, excel_file_name: '报修类别' })
}

const API_MAP = {
  query: queryApi,
  add: addApi,
  edit: editApi,
  delete: deleteApi,
  detail: detailApi,
  import: importApi,
  export: exportApi,
}
// #endregion

// #region (page init)
function init() {
  queryApi()
}
init()
// #endregion

</script>

<template>
  <div class="card flex-grow flex flex-col">
    <div class="flex justify-between">
      <div>
        <import-button @success="queryApi" :importKey="('cs_pid=837')" :url="URL_CUT_REF"
          :exportKey="('cs_pid=837')"></import-button>
        <el-button @click="handleTableRowBtn_export" type="primary">导出</el-button>
        <el-button @click="handleTableRowBtn_add" type="primary">新增</el-button>
        <el-button @click="handleTableRowBtn_delete" type="danger">删除</el-button>
      </div>
      <el-form inline :model="queryForm_Data">
        <!-- <el-form-item label="关键字"><el-input v-model="queryForm_Data.keyword" ></el-input></el-form-item> -->
        <!-- <el-form-item label="上级编号">
        <el-input v-model="queryForm_Data.cs_pid" clearable />
      </el-form-item> -->
        <el-form-item label="类别名称">
          <el-input v-model="queryForm_Data.cs_name" clearable />
        </el-form-item>
        <!-- <el-form-item label="字典编号">
        <el-input v-model="queryForm_Data.cs_code" clearable />
      </el-form-item>
      <el-form-item label="排序编号">
        <el-input v-model="queryForm_Data.cs_sort" clearable />
      </el-form-item>
      <el-form-item label="字典层级(备用)">
        <el-input v-model="queryForm_Data.cs_level" clearable />
      </el-form-item>
      <el-form-item label="字典路径(备用)">
        <el-input v-model="queryForm_Data.cs_path" clearable />
      </el-form-item>
      <el-form-item label="字典类型">
        <el-select v-model="queryForm_Data.cs_zdlx" clearable filterable>
          <el-option label="自定义" value="1" />
          <el-option label="地方" value="2" />
          <el-option label="国标" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否启用">
        <el-select v-model="queryForm_Data.cs_sfqy" clearable filterable>
          <el-option label="未启用" value="0" />
          <el-option label="已启用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="数据类型">
        <el-input v-model="queryForm_Data.cs_sjlx" clearable />
      </el-form-item>
      <el-form-item label="数据长度">
        <el-input v-model="queryForm_Data.cs_sjcd" clearable />
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="queryForm_Data.cs_bz" clearable />
      </el-form-item>
      <el-form-item label="父级code">
        <el-input v-model="queryForm_Data.cs_pcode" clearable />
      </el-form-item> -->
        <el-form-item>
          <el-button @click="handleQueryFormBtn_search" type="primary">搜索</el-button>
          <!-- <el-button @click="handleQueryFormBtn_clear" type="warning">清空</el-button> -->
        </el-form-item>
      </el-form>
    </div>
    <div class="divider"></div>
    <div class="flex-auto">
      <el-table :data="tableData" @selection-change="handleSelectionChange" v-loading="loading_table"
        element-loading-background="#ffffff70">
        <el-table-column type="selection"></el-table-column>
        <el-table-column prop="cs_id" label="编号" width="auto" show-overflow-tooltip></el-table-column>
        <!-- <el-table-column prop="cs_pid" label="上级编号" width="auto" show-overflow-tooltip></el-table-column> -->
        <el-table-column prop="cs_name" label="报修类别名称" width="auto" show-overflow-tooltip></el-table-column>
        <!-- <el-table-column prop="cs_code" label="字典编号" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="cs_sort" label="排序编号" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="cs_level" label="字典层级(备用)" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="cs_path" label="字典路径(备用)" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="cs_zdlx" label="字典类型" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="cs_sfqy" label="是否启用" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="cs_sjlx" label="数据类型" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="cs_sjcd" label="数据长度" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="cs_bz" label="备注" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="cs_pcode" label="父级code" width="auto" show-overflow-tooltip></el-table-column> -->
        <el-table-column label="操作" fixed="right">
          <template #default="scope">
            <el-button link :auto-insert-space="false" @click="handleTableColBtn_edit(scope)" type="primary">编辑
            </el-button>
            <el-button link :auto-insert-space="false" @click="handleTableColBtn_delete(scope)" type="primary">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="flex justify-end mt-10 py-4">
      <el-pagination :page-size="limit" v-model:current-page="currentPage" @current-change="handleCurrentChange"
        background layout="total, prev, pager, next" :total="total" />
    </div>
  </div>

  <el-dialog v-model="dialogVisible_addOrEdit" append-to-body destroy-on-close>
    <el-form :model="dialogForm_Data" ref="dialogForm_Ref_addOrEdit" :rules="dialogForm_Rules_addOrEdit"
      label-width="120px">
      <!-- <el-form-item label="上级编号" prop="cs_pid">
        <el-input v-model="dialogForm_Data.cs_pid" clearable />
      </el-form-item> -->
      <el-form-item label="报修类别名称" prop="cs_name">
        <el-input v-model="dialogForm_Data.cs_name" clearable />
      </el-form-item>
      <!-- <el-form-item label="字典编号" prop="cs_code">
        <el-input v-model="dialogForm_Data.cs_code" clearable />
      </el-form-item>
      <el-form-item label="排序编号" prop="cs_sort">
        <el-input v-model="dialogForm_Data.cs_sort" clearable />
      </el-form-item>
      <el-form-item label="字典层级(备用)" prop="cs_level">
        <el-input v-model="dialogForm_Data.cs_level" clearable />
      </el-form-item>
      <el-form-item label="字典路径(备用)" prop="cs_path">
        <el-input v-model="dialogForm_Data.cs_path" clearable />
      </el-form-item>
      <el-form-item label="字典类型" prop="cs_zdlx">
        <el-radio-group v-model="dialogForm_Data.cs_zdlx">
          <el-radio label="1">自定义</el-radio>
          <el-radio label="2">地方</el-radio>
          <el-radio label="3">国标</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否启用" prop="cs_sfqy">
        <el-radio-group v-model="dialogForm_Data.cs_sfqy">
          <el-radio label="0">未启用</el-radio>
          <el-radio label="1">已启用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="数据类型" prop="cs_sjlx">
        <el-input v-model="dialogForm_Data.cs_sjlx" clearable />
      </el-form-item>
      <el-form-item label="数据长度" prop="cs_sjcd">
        <el-input v-model="dialogForm_Data.cs_sjcd" clearable />
      </el-form-item>
      <el-form-item label="备注" prop="cs_bz">
        <el-input v-model="dialogForm_Data.cs_bz" clearable />
      </el-form-item>
      <el-form-item label="父级code" prop="cs_pcode">
        <el-input v-model="dialogForm_Data.cs_pcode" clearable />
      </el-form-item> -->
      <div class="flex justify-center">
        <el-button @click="handleDialogFormBtn_submit('dialogForm_Ref_addOrEdit')" type="primary">提交</el-button>
        <el-button @click="handleDialogFormBtn_cancel('dialogForm_Ref_addOrEdit')" type="default">取消</el-button>
      </div>
    </el-form>
  </el-dialog>
</template>
