<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 = '{{tableKey}}'
const URL_CUT = '{{url}}'
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;
  {{#each tableColFields}}
  '{{prop}}': string; // {{label}}
  {{/each}}
}
// #endregion

// #region (props)
{{#if props}}
const props = defineProps<{
  {{#each props}}
  {{this}}: string,
  {{/each}}
}>()
{{/if}}
// #endregion

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

{{#each queryFormBtnList}}
const handleQueryFormBtn_{{name}} = {{{click}}}
{{/each}}
// #endregion

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

// #region (table row)
{{#each tableRowBtnList}}
const handleTableRowBtn_{{name}} = {{{click}}}
{{/each}}
// #endregion

// #region (table body)
const tableData = ref<TYPE_TABLE_FIELD[]>([])
const DetailName = '{{detailName}}'
const DetailParam = '{{detailParam}}'

{{#each tableColBtnList}}
const handleTableColBtn_{{name}} = {{{click}}}
{{/each}}
// #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 }>({})

{{#each dialogFormBtnList}}
const handleDialogFormBtn_{{name}} = {{{click}}}
{{/each}}
// #endregion

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

const dialogForm_Ref_addOrEdit= ref<FormInstance>()
const dialogForm_Rules_addOrEdit = reactive({ 
  {{#each dialogFormFields}}
  '{{value}}':{required : true,message:'{{label}}不能为空',trigger:'submit'},
  {{/each}}
})
// #endregion

// #region (dialog audit)
const dialogVisible_audit = ref<boolean>(false)

const dialogForm_Field_audit= reactive<{
  FLAG:keyof TYPE_TABLE_FIELD,
  REASON?:keyof TYPE_TABLE_FIELD
}>({
  FLAG:'{{tableKey}}',
  // REASON:'{{tableKey}}'
})

const dialogForm_Ref_audit= ref<FormInstance>()
const dialogForm_Rules_audit = reactive<FormRules>({ 
  {{#each dialogFormFields}}
  '{{value}}':{required : true ,message:'{{label}}不能为空',trigger:'submit'},
  {{/each}}
})

// #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
    }
  }).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,[{{#each dialogFormFields}}'{{value}}',{{/each}}]),
    }
  })
}

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(){
  return download(URL_CUT + '/index', queryForm_Data.value)
}

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">
    <el-form inline :model="queryForm_Data">
      <!-- <el-form-item label="关键字"><el-input v-model="queryForm_Data.keyword" ></el-input></el-form-item> -->
      {{#each queryFormFields}}
      <el-form-item label="{{label}}">{{> WhichFormItem form="queryForm_Data"}}</el-form-item>
      {{/each}}
      {{#if queryFormBtnList}}
      <el-form-item>
        {{#each queryFormBtnList}}
        <el-button @click="handleQueryFormBtn_{{name}}" type="{{type}}">{{ label }}</el-button>
        {{/each}}
      </el-form-item>
      {{/if}}
    </el-form>
    <div class="divider"></div>
    <div>
      {{#each tableRowBtnList}}
        {{#if (equals $import true)}}
        <import-button :url="URL_CUT_REF"></import-button>
        {{else}}
        <el-button @click="handleTableRowBtn_{{name}}" type="{{type}}">{{ label }}</el-button>
        {{/if}}
      {{/each}}
    </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>
        {{#each tableColFields}}
        <el-table-column prop="{{prop}}" label="{{label}}" width="auto" show-overflow-tooltip></el-table-column>
        {{/each}}
        {{#if tableColBtnList}}
        <el-table-column label="操作" fixed="right">
          <template #default="scope">
            {{#each tableColBtnList}}
            <el-button link :auto-insert-space="false" @click="handleTableColBtn_{{name}}(scope)" type="{{type}}" >{{
              label }}</el-button>
            {{/each}}
          </template>
        </el-table-column>
        {{/if}}
      </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">
      {{#each dialogFormFields}}
      <el-form-item label="{{label}}" prop="{{value}}">{{> WhichFormItem form="dialogForm_Data"}}</el-form-item>
      {{/each}}
      {{#if dialogFormBtnList}}
      <div class="flex justify-center">
        {{#each dialogFormBtnList}}
        <el-button @click="handleDialogFormBtn_{{name}}('dialogForm_Ref_addOrEdit')" type="{{type}}">{{ label }}</el-button>
        {{/each}}
      </div>
      {{/if}}
    </el-form>
  </el-dialog>

  <el-dialog v-model="dialogVisible_audit" append-to-body destroy-on-close>
    <el-form :model="dialogForm_Data" ref="dialogForm_Ref_audit" :rules="dialogForm_Rules_audit" label-width="120px">
      <el-form-item label="状态">
        <el-radio-group v-model="dialogForm_Data[dialogForm_Field_audit.FLAG]">
          <el-radio label="1">通过</el-radio>
          <el-radio label="2">未通过</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- <el-form-item label="原因" v-show="dialogForm_Data[dialogForm_Field_audit.FLAG] === '1'">
        <el-input type="textarea" v-model="dialogForm_Data[dialogForm_Field_audit.REASON]" :rows="5" />
      </el-form-item> -->
      <div class="flex justify-center">
        {{#each dialogFormBtnList}}
        <el-button @click="handleDialogFormBtn_{{name}}('dialogForm_Ref_audit')" type="{{type}}">{{ label }}</el-button>
        {{/each}}
      </div>
    </el-form>
  </el-dialog>
</template>
