<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'
import { user } from "~/store/user";

// #region (constant)
const TABLE_KEY = 'xhsl_id'
const URL_CUT = '/xdhq/hqgl_splcsz'
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 审核人
let userList = ref([]);
request({
  url: '/user/main/index',
  data: {
    limit: 999,
    page: 1,
    admin: 1,
    dept_id: user.uo_id
  }
}).then(res => {
  if (res.code == '1') {
    userList.value = res.data.page_data;
  }
})
//#endregion

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

// #region (type)
type TYPE_TABLE_FIELD = {
  [TABLE_KEY]: string;
  'xhsl_mc': string; // 审批流程编名称
  'xhsl_sz': string; // 流程设置JSON
  'xhsl_cjr': string; // 创建人
  'xhsl_cjsj': string; // 创建时间
}
// #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 = {}
  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 DetailName = '-SPLCSZ-DETAIL'
const DetailParam = 'aid'

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_detail = (scope: { row: TYPE_TABLE_FIELD }) => {
  router.push({ name: DetailName, params: { [DetailParam]: scope.row[TABLE_KEY] } })
}
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 }))
    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({
  'xhsl_mc': { required: true, message: '审批流程编名称不能为空', trigger: 'submit' },
  'xhsl_sz': { required: true, message: '流程设置JSON不能为空', trigger: 'submit' },
  'xhsl_cjr': { required: true, message: '创建人不能为空', trigger: 'submit' },
  'xhsl_cjsj': { required: true, message: '创建时间不能为空', 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
    }
  }).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
    if (data.page_data.length === 1) {
      dialogForm_Data.value = data.page_data[0]
      whichDialogSubmit = 'edit'
    } else if (data.page_data.length === 0) {
      whichDialogSubmit = 'add'
    }
    else {
      throw new Error('联系开发者')
    }

    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, ['xhsl_mc', 'xhsl_sz', 'xhsl_cjr', 'xhsl_cjsj',]),
    }
  })
}

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})
}

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>
      <el-form-item label="审批流程编名称">
        <el-input v-model="queryForm_Data.xhsl_mc" clearable />
      </el-form-item>
      <el-form-item label="流程设置JSON">
        <el-input v-model="queryForm_Data.xhsl_sz" type="textarea" />
      </el-form-item>
      <el-form-item label="创建人">
        <el-input v-model="queryForm_Data.xhsl_cjr" clearable />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker type="datetime" v-model="queryForm_Data.xhsl_cjsj" value-format="YYYY-MM-DD HH:mm:ss"
          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 class="divider"></div>
    <div>
      <import-button @success="queryApi" :url="URL_CUT_REF"></import-button>
      <el-button @click="handleTableRowBtn_export" type="success">导出</el-button>
      <el-button @click="handleTableRowBtn_add" type="primary">新增</el-button>
      <el-button @click="handleTableRowBtn_delete" type="danger">删除</el-button>
    </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="xhsl_mc" label="审批流程编名称" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="xhsl_sz" label="流程设置JSON" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="xhsl_cjr" label="创建人" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="xhsl_cjsj" label="创建时间" 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_detail(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="xhsl_mc">
        <el-input v-model="dialogForm_Data.xhsl_mc" clearable />
      </el-form-item>
      <el-form-item label="流程设置JSON" prop="xhsl_sz">
        <el-input v-model="dialogForm_Data.xhsl_sz" type="textarea" />
      </el-form-item>
      <el-form-item label="创建人" prop="xhsl_cjr">
        <el-input v-model="dialogForm_Data.xhsl_cjr" clearable />
      </el-form-item>
      <el-form-item label="创建时间" prop="xhsl_cjsj">
        <el-date-picker type="datetime" v-model="dialogForm_Data.xhsl_cjsj" value-format="YYYY-MM-DD HH:mm:ss"
          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> -->

  <el-form :model="dialogForm_Data" ref="dialogForm_Ref_addOrEdit" :rules="dialogForm_Rules_addOrEdit"
    label-width="120px" v-if="!loading_table">
    <el-form-item label="审批流程名称" prop="xhsl_mc">
      <el-input v-model="dialogForm_Data.xhsl_mc" clearable />
    </el-form-item>
    <el-form-item label="流程设置" prop="xhsl_sz">
      <str-to-json v-model="dialogForm_Data.xhsl_sz" type="arr">
        <template #default="{ value, change }">
          <div class="mb-4">
            <el-button @click="value.push({ sign: '1', val_1: 0, val_2: 0, spr: '', jwhtl: '1' })">新增</el-button>
          </div>


          <div v-for="(item, idx) in value" class="w-full flex flex-wrap py-1 items-center">
            <div class="min-w-470px">
              <span class="mr-4">申购金额</span>
              <div class="flex">
                <el-select v-model="item.sign" size="default" class="w-90px mr-5px">
                  <el-option value="1" label="小于"></el-option>
                  <el-option value="2" label="介于"></el-option>
                  <el-option value="3" label="大于"></el-option>
                </el-select>
                <el-input-number v-show="item.sign !== '3'" v-model="item.val_1" size="default"
                  controls-position="right">
                </el-input-number>
                <el-input-number v-show="item.sign !== '1'" v-model="item.val_2" size="default"
                  controls-position="right">
                </el-input-number>
              </div>
            </div>
            <div class="ml-2 flex items-center">
              <span class="mr-4">审批人</span>
              <span class="flex">
                <el-select v-model="item.spr">
                  <el-option v-for="(user,index) in userList" :key="index" :label="user.user_realname" :value="user.user_realname"></el-option>
                </el-select>
                <!-- <el-input v-model="item.spr" size="default" class="mr-2"></el-input> -->
                <el-checkbox v-model="item.jwhtl" label="校务会讨论" size="default" true-label="1" false-label="2" />
              </span>
            </div>
            <div class="ml-2  items-center">
              <el-button @click="value.splice(idx, 1)" type="danger" size="default">移除</el-button>
            </div>

          </div>
        </template>
      </str-to-json>

    </el-form-item>
    <!-- <el-form-item label="创建人" prop="xhsl_cjr">
      <el-input v-model="dialogForm_Data.xhsl_cjr" clearable />
    </el-form-item>
    <el-form-item label="创建时间" prop="xhsl_cjsj">
      <el-date-picker type="datetime" v-model="dialogForm_Data.xhsl_cjsj" value-format="YYYY-MM-DD HH:mm:ss"
        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>

</template>
