<script>
import { defineComponent, ref, getCurrentInstance, reactive } from "@vue/composition-api";
import request, { download } from '~/utils/request';
import { Message } from 'element-ui'

export default defineComponent({
  props: [],
  setup(props) {
    const _this = getCurrentInstance().proxy;
    // #region (constant)
    const TABLE_KEY = 'jxtj_id'
    const URL_CUT = '/jdbg/xxgzjc_bbtj'
    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;
    //
    //   'jxtj_name': string; // 报表名称
    //
    //   'jxtj_cjsj': string; // 创建时间
    //
    //   'jxtj_content_json': string; // 报表内容JSON
    //
    //   'jxj_id': 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()
    }

    const handleTableColBtn_export = async () => {
      if (multipleSelection.value?.length) {
        request({
          url: '/jdbg/xxgzjc_bbtj/zip',
          data: {
            jxtj_ids: multipleSelection.value.map((item) => item[TABLE_KEY]).join()
          }
        }).then(res => {
          // console.log('res :>> ', res);
          if (res.code === '1') {
            download(res.data.files)
          }
        })
      } else {
        Message.info("请先勾选文件")
      }
    }
    // #endregion

    // #region (table body)
    const tableData = ref([])
    const DetailName = '-XXGZJC-BBTJ'
    const DetailParam = 'aid'

    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]} })
      dialogData_detail.value = {
        title: scope.row.jxtj_name,
        table: JSON.parse(scope.row.jxtj_content_json)
      }
      dialogVisible_detail.value = true
    }
    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({
      'jxtj_name': { required: true, message: '报表名称不能为空', trigger: 'submit' },
      'jxtj_cjsj': { required: true, message: '创建时间不能为空', trigger: 'submit' },
      'jxtj_content_json': { required: true, message: '报表内容不能为空', trigger: 'submit' },
      'jxj_id': { 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_detail = ref(false)
    const dialogData_detail = ref({
      title: '',
      table: []
    })

    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_detail,
      dialogData_detail,

      handleTableColBtn_export
    }
  }
})
</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.jxtj_name" clearable /></el-form-item>
      <el-form-item label="创建时间"><el-date-picker type="date" v-model="queryForm_Data.jxtj_cjsj" value-format="yyyy-MM-dd" clearable /></el-form-item>
      <el-form-item label="报表内容JSON"><el-input v-model="queryForm_Data.jxtj_content_json" type="textarea" /></el-form-item>
      <el-form-item label="关联检查任务"><el-input v-model="queryForm_Data.jxj_id" 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="handleTableColBtn_export" 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="jxtj_name" label="报表名称" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="jxtj_cjsj" label="创建时间" width="auto" show-overflow-tooltip></el-table-column>
        <!-- <el-table-column prop="jxtj_content_json" label="报表内容JSON" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="jxj_id" 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="jxtj_name">
          <el-input v-model="dialogForm_Data.jxtj_name" clearable />
        </el-form-item>
        <el-form-item label="创建时间" prop="jxtj_cjsj">
          <el-date-picker type="date" v-model="dialogForm_Data.jxtj_cjsj" value-format="yyyy-MM-dd" clearable />
        </el-form-item>
        <el-form-item label="报表内容JSON" prop="jxtj_content_json">
          <el-input v-model="dialogForm_Data.jxtj_content_json" type="textarea" />
        </el-form-item>
        <el-form-item label="关联检查任务" prop="jxj_id">
          <el-input v-model="dialogForm_Data.jxj_id" 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_detail" append-to-body destroy-on-close title="查看报表详情" width="900px">
      <el-table :data="dialogData_detail.table">
        <el-table-column :label="dialogData_detail.title" align="center">
          <el-table-column type="index" width="50" label="序号" show-overflow-tooltip></el-table-column>
          <el-table-column prop="school_name" label="学校名称" show-overflow-tooltip></el-table-column>
          <el-table-column prop="file_num" width="70" label="提交文件数量" show-overflow-tooltip></el-table-column>
          <el-table-column prop="last_date" width="130" label="提交时间（最后一个文件）" show-overflow-tooltip></el-table-column>
          <el-table-column prop="suggest" label="检查意见" show-overflow-tooltip></el-table-column>
          <el-table-column prop="issue" label="学校的问题和困难" show-overflow-tooltip></el-table-column>

        </el-table-column>
      </el-table>
    </el-dialog>
  </div>



</template>
