<script>
import { defineComponent, ref, getCurrentInstance, reactive } from "@vue/composition-api";
import request from '~/utils/request';
import { Message } from 'element-ui'
import { pick } from 'lodash-es';
import RemoteSelect from '~/components/RemoteSelect/index.vue';
import FileUpload from '~/components/FileUpload/index.vue';

export default defineComponent({
  props: [],
  components: { RemoteSelect, FileUpload },
  setup(props) {
    const _this = getCurrentInstance().proxy;
    // #region (constant)
    const TABLE_KEY = 'jxk_id'
    const URL_CUT = '/jdbg/xxgzjc_ksfz'
    const URL_CUT_REF = ref(URL_CUT)
    const URL_SUBMIT_KEY = URL_CUT.split('/').join('_').slice(1)
    const instance = getCurrentInstance().proxy
    // #endregion

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

    // #region (type)
    // type TYPE_TABLE_FIELD = {
    //   [TABLE_KEY]: string;
    //
    //   'jxk_name': string; // 科室名称
    //
    //   'jxk_template_num': string; // 已传模板数量
    //
    // }
    // #endregion

    // #region (query row)
    const queryForm_Data = ref({})

    const handleQueryFormBtn_search = () => {
      queryApi()
    }
    // #endregion

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

    // #region (table row)
    const handleTableRowBtn_add = () => {
      whichDialogSubmit = 'add'
      dialogForm_Data.value = {}
      dialogVisible_addOrEdit.value = true
    }
    const handleTableRowBtn_delete = async () => {
      if (!multipleSelection.value?.length) return Message.info('请先勾选文件')

      await deleteApi(multipleSelection.value.map((item) => item[TABLE_KEY]))
      queryApi()
    }
    // #endregion

    // #region (table body)
    const tableData = ref([])
    const DetailName = 'XXGZJC_DZMB_DETAIL'
    const DetailParam = 'id'

    const handleTableColBtn_edit = async (scope) => {
      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) => {
      instance.$router.push({ name: DetailName, params: { [DetailParam]: scope.row[TABLE_KEY] }, query: { name: scope.row.jxk_name } })
    }
    const handleTableColBtn_delete = async (scope) => {
      await deleteApi(scope.row[TABLE_KEY])
      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({})

    const handleDialogFormBtn_submit = async (formRefKey, extendData) => {
      const isValid = await (instance?.$refs[formRefKey]).validate()
      if (isValid) {
        await API_MAP[whichDialogSubmit](({ ...dialogForm_Data.value, ...extendData }))
        handleDialogFormBtn_cancel()
        queryApi()
      }
    }
    const handleDialogFormBtn_cancel = (formRefKey) => {
      dialogVisible_addOrEdit.value = false
    }
    // #endregion

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

    const dialogForm_Ref_addOrEdit = ref()
    const dialogForm_Rules_addOrEdit = reactive({
      'jxk_name': { required: true, message: '科室名称不能为空', trigger: 'submit' },
      'jxk_template_num': { 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) => {
        const { data } = response
        total.value = parseInt(data.total_rows)
        tableData.value = data.page_data
        return response
      }).then(() => {
        loading_table.value = false
      })
    }

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

    function editApi(data) {
      return request({
        url: URL_CUT + '/edit',
        data: {
          [TABLE_KEY]: data[TABLE_KEY],
          [URL_SUBMIT_KEY]: {},
        }
      })
    }

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

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

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

    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

    const dialogVisible_addOrEdit_example = ref(false)
    const dialogForm_Ref_addOrEdit_example = ref()
    const dialogForm_Rules_addOrEdit_example = ref({
      'jxkm_name': { required: true, message: '模板名称不能为空', trigger: 'submit' },
      'jxkm_date': { required: true, message: '发布日期不能为空', trigger: 'submit' },
      'jxkm_status': { required: true, message: '发布状态不能为空', trigger: 'submit' },
      'jxk_id': { required: true, message: '所属科室分组不能为空', trigger: 'submit' },
    })
    const dialogForm_Data_example = ref({})
    function handleTableRowBtn_add_example() {
      dialogForm_Data_example.value = {}
      dialogVisible_addOrEdit_example.value = true
    }
    const handleDialogFormBtn_submit_example = async (formRefKey, extendData) => {
      const isValid = await (instance?.$refs[formRefKey]).validate()
      if (isValid) {
        await request({
          url: '/jdbg/xxgzjc_ksmb/add',
          data: {
            'jdbg_xxgzjc_ksmb': pick(dialogForm_Data_example.value, ['jxkm_name', 'jxkm_date', 'jxkm_status', 'jxk_id', 'jxkm_file']),
          }
        })
        dialogVisible_addOrEdit_example.value = false
        queryApi()
      }
    }

    return {
      queryForm_Data,
      loading_table,
      tableData,
      dialogVisible_addOrEdit,
      dialogForm_Ref_addOrEdit,
      dialogForm_Rules_addOrEdit,
      dialogForm_Data,
      limit,
      currentPage,
      total,
      handleCurrentChange,
      handleQueryFormBtn_search,
      handleTableRowBtn_add,
      handleTableColBtn_delete,
      handleTableColBtn_detail,
      handleTableColBtn_edit,
      handleSelectionChange,
      handleTableRowBtn_delete,
      handleDialogFormBtn_submit,
      handleDialogFormBtn_cancel,

      dialogVisible_addOrEdit_example,
      dialogForm_Ref_addOrEdit_example,
      dialogForm_Rules_addOrEdit_example,
      dialogForm_Data_example,
      handleTableRowBtn_add_example,
      handleDialogFormBtn_submit_example
    }
  }
})
</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.jxk_name" clearable />
      </el-form-item>
      <!-- <el-form-item label="已传模板数量"><el-input v-model="queryForm_Data.jxk_template_num" clearable /></el-form-item> -->
      <el-form-item>
        <el-button @click="handleQueryFormBtn_search" type="primary">搜索</el-button>
      </el-form-item>
    </el-form>
    <div class="divider"></div>
    <div>
      <el-button @click="handleTableRowBtn_add" type="primary">新增科室</el-button>
      <el-button @click="handleTableRowBtn_add_example" 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="jxk_name" label="科室名称" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="jxk_template_num" 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="text">编辑</el-button> -->
            <el-button link :auto-insert-space="false" @click="handleTableColBtn_detail(scope)" type="text">详情
            </el-button>
            <el-button link :auto-insert-space="false" @click="handleTableColBtn_delete(scope)" type="text">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

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

    <el-dialog :visible.sync="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="jxk_name">
          <el-input v-model="dialogForm_Data.jxk_name" clearable />
        </el-form-item>
        <!-- <el-form-item label="已传模板数量" prop="jxk_template_num"><el-input v-model="dialogForm_Data.jxk_template_num" 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-dialog :visible.sync="dialogVisible_addOrEdit_example" append-to-body destroy-on-close>
      <el-form :key="dialogVisible_addOrEdit_example" :model="dialogForm_Data_example"
        ref="dialogForm_Ref_addOrEdit_example" :rules="dialogForm_Rules_addOrEdit_example" label-width="120px">
        <el-form-item label="模板名称" prop="jxkm_name">
          <el-input v-model="dialogForm_Data_example.jxkm_name" clearable />
        </el-form-item>
        <el-form-item label="所属科室分组" prop="jxk_id">
          <RemoteSelect v-model="dialogForm_Data_example.jxk_id" url="/jdbg/xxgzjc_ksfz/index"
            field="jxk_id,jxk_name" />
        </el-form-item>
        <el-form-item label="模板文件" prop="jxkm_file">
          <FileUpload :part.sync="dialogForm_Data_example.jxkm_file" :limit="1" clearable />
        </el-form-item>
        <div class="flex justify-center">
          <el-button @click="handleDialogFormBtn_submit_example('dialogForm_Ref_addOrEdit_example')" type="primary">提交
          </el-button>
          <el-button @click="dialogVisible_addOrEdit_example = false" type="default">取消
          </el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>



</template>
