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

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

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

    // #region (type)
    // type TYPE_TABLE_FIELD = {
    //   [TABLE_KEY]: string;
    //
    //   'jxkm_name': string; // 模板名称
    //
    //   'jxkm_date': string; // 发布日期
    //
    //   'jxkm_status': string; // 发布状态
    //
    //   'jxk_id': string; // 所属科室分组
    //
    // }
    // #endregion

    // #region (query row)
    const queryForm_Data = ref({
      jxk_id: props.id
    })

    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 = 'bid'

    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 dialogVisible_detail = ref(false)
    const dialogForm_detail_Data = ref()
    const handleTableColBtn_detail = (scope) => {
      // instance.$router.push({ name: DetailName, params: { [DetailParam]: scope.row[TABLE_KEY] } })
      download2(scope.row.jxkm_file, null, scope.row.jxkm_name)
      // dialogForm_detail_Data.value = scope.row.jxkm_file
      // 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({
      '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' },
    })
    // #endregion

    async function handleTableColBtn_publish(scope) {
      await editApi({ ...scope.row, jxkm_date: (new Date()).toLocaleDateString(), jxkm_status: '1' })
      queryApi()
    }

    // #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, jxk_id: props.id },
        }
      })
    }

    function editApi(data) {
      return request({
        url: URL_CUT + '/edit',
        data: {
          [TABLE_KEY]: data[TABLE_KEY],
          [URL_SUBMIT_KEY]: pick(data, ['jxkm_name', 'jxkm_date', 'jxkm_status', 'jxk_id', 'jxkm_file']),
        }
      })
    }

    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

    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,

      route,
      handleTableColBtn_publish,
      dialogVisible_detail,
      dialogForm_detail_Data,

    }
  }
})
</script>


<template>
  <div class="card flex-grow flex flex-col">
    <div class="pre">{{ route.query.name }}</div>
    <div class="divider my-4"></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.jxkm_name" clearable />
      </el-form-item>
      <!-- <el-form-item label="发布日期">
        <el-date-picker type="date" v-model="queryForm_Data.jxkm_date" value-format="yyyy-MM-dd"
          clearable />
      </el-form-item> -->
      <el-form-item label="发布状态">
        <el-select v-model="queryForm_Data.jxkm_status" clearable filterable>
          <el-option label="已发布" value="1" />
          <el-option label="未发布" value="2" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="所属科室分组">
        <el-input v-model="queryForm_Data.jxk_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="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="jxkm_name" label="模板名称" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="jxkm_date" label="发布日期" width="auto" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.jxkm_status_option_k === '1' ? scope.row.jxkm_date : '--' }}
          </template>
        </el-table-column>
        <el-table-column prop="jxkm_status" label="发布状态" width="auto" show-overflow-tooltip></el-table-column>
        <!-- <el-table-column prop="jxk_id" label="所属科室分组" width="auto" show-overflow-tooltip></el-table-column> -->
        <el-table-column label="操作" fixed="right">
          <template #default="scope">
            <el-button :disabled="scope.row.jxkm_status_option_k === '1'" link :auto-insert-space="false"
              @click="handleTableColBtn_publish(scope)" type="text">发布
            </el-button>
            <!-- <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 :key="dialogVisible_addOrEdit" :model="dialogForm_Data" ref="dialogForm_Ref_addOrEdit"
        :rules="dialogForm_Rules_addOrEdit" label-width="120px">
        <el-form-item label="模板名称" prop="jxkm_name">
          <el-input v-model="dialogForm_Data.jxkm_name" clearable />
        </el-form-item>
        <!-- <el-form-item label="发布日期" prop="jxkm_date">
          <el-date-picker type="datetime" v-model="dialogForm_Data.jxkm_date" value-format="yyyy-MM-dd HH:mm:ss"
            clearable />
        </el-form-item>
        <el-form-item label="发布状态" prop="jxkm_status">
          <el-radio-group v-model="dialogForm_Data.jxkm_status">
            <el-radio label="1">已发布</el-radio>
            <el-radio label="2">未发布</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属科室分组" prop="jxk_id">
          <el-input v-model="dialogForm_Data.jxk_id" clearable />
        </el-form-item> -->
        <el-form-item label="模板文件" prop="jxkm_file">
          <FileUpload :part.sync="dialogForm_Data.jxkm_file" :limit="1" 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>
      <FilePreview :key="dialogForm_detail_Data" :url="dialogForm_detail_Data" class="min-w-400px min-h-300px"></FilePreview>
    </el-dialog> -->
  </div>



</template>
