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

export default defineComponent({
  props: [],
  setup(props) {
    const _this = getCurrentInstance().proxy;
    // #region (constant)
    const TABLE_KEY = 'jxj_id'
    const URL_CUT = '/jdbg/xxgzjc_jcrw'
    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;
    //
    //   'jxj_title': string; // 检查任务标题
    //
    //   'jxj_fqr': string; // 发起人
    //
    //   'jxj_wcsj': string; // 完成时间
    //
    //   'jxj_wcqk': string; // 完成情况
    //
    //   'jxj_content': string; // 检查任务内容
    //
    //   'jxj_xfdx_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 () => {
      await deleteApi(multipleSelection.value.map((item) => item[TABLE_KEY]))
      queryApi()
    }
    // #endregion

    // #region (table body)
    const tableData = ref([])
    const DetailName = 'XXGZJC_TJTJ_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] } })
    }
    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, jxj_xfdx_json: dialogForm_Data.value.jxj_xfdx_json?.join() }))
        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({
      'jxj_title': { required: true, message: '检查任务标题不能为空', trigger: 'submit' },
      'jxj_fqr': { required: true, message: '发起人不能为空', trigger: 'submit' },
      'jxj_wcsj': { required: true, message: '完成时间不能为空', trigger: 'submit' },
      'jxj_wcqk': { required: true, message: '完成情况不能为空', trigger: 'submit' },
      'jxj_content': { required: true, message: '检查任务内容不能为空', trigger: 'submit' },
      'jxj_xfdx_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, jxj_fqr: user.real_name },
        }
      })
    }

    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

    function handleTree(list) {
      return list.map(item => {
        const obj = Object.assign({
          value: `${item.id}|${item.label}`
        }, item)
        if (item.children) {
          obj.children = handleTree(item.children)
        }
        return obj
      })

    }

    let orgTree = ref()
    const cascaderRef = ref()
    request({
      url: '/user/org/list_tree',
      data: {
        uo_pid: 1036
      }
    }).then(res => {
      if (res.code === '1') {
        orgTree.value = handleTree(res.data.one_info)
        console.log('orgTree :>> ', orgTree.value);
      }
    })

    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,

      orgTree,
      cascaderRef
    }
  }
})
</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.jxj_title" clearable /></el-form-item>
      <el-form-item label="发起人"><el-input v-model="queryForm_Data.jxj_fqr" clearable /></el-form-item>
      <el-form-item label="完成时间"><el-date-picker type="date" v-model="queryForm_Data.jxj_wcsj" value-format="yyyy-MM-dd" clearable /></el-form-item>
      <el-form-item label="完成情况"><el-input v-model="queryForm_Data.jxj_wcqk" clearable /></el-form-item>
      <el-form-item label="检查任务内容"><el-input v-model="queryForm_Data.jxj_content" type="textarea" /></el-form-item>
      <el-form-item label="下发对象JSON"><el-input v-model="queryForm_Data.jxj_xfdx_json" type="textarea" /></el-form-item>
      <el-form-item label="归档状态"><el-select v-model="queryForm_Data.jxj_id" clearable filterable ><el-option label="是" value="1" /><el-option label="否" value="2" /></el-select></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="jxj_title" label="检查任务标题" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="jxj_fqr" label="发起人" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="jxj_wcsj" label="完成时间" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="jxj_wcqk" label="完成情况" width="auto" show-overflow-tooltip>
          <template #default="scope">
            <el-progress :percentage="scope.row.jxj_wcqk * 1"></el-progress>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="jxj_content" label="检查任务内容" width="auto" show-overflow-tooltip></el-table-column>
        <el-table-column prop="jxj_xfdx_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="jxj_title">
          <el-input v-model="dialogForm_Data.jxj_title" clearable />
        </el-form-item>
        <!-- <el-form-item label="发起人" prop="jxj_fqr">
          <el-input v-model="dialogForm_Data.jxj_fqr" clearable />
        </el-form-item> -->
        <el-form-item label="完成时间" prop="jxj_wcsj">
          <el-date-picker type="date" v-model="dialogForm_Data.jxj_wcsj" value-format="yyyy-MM-dd" clearable />
        </el-form-item>
        <!-- <el-form-item label="完成情况" prop="jxj_wcqk">
          <el-input v-model="dialogForm_Data.jxj_wcqk" clearable />
        </el-form-item> -->
        <el-form-item label="检查任务内容" prop="jxj_content">
          <el-input v-model="dialogForm_Data.jxj_content" type="textarea" :rows="6" />
        </el-form-item>
        <el-form-item label="下发对象" prop="jxj_xfdx_json">
          <el-cascader ref="cascaderRef" class="w-full" v-model="dialogForm_Data.jxj_xfdx_json" filterable
            reserve-keyword clearable :props="{ checkStrictly: false, multiple: true, emitPath: false }"
            :options="orgTree" :show-all-levels="false" />
        </el-form-item>
        <!-- <el-form-item label="归档状态" prop="jxj_id">
          <el-radio-group v-model="dialogForm_Data.jxj_id">
            <el-radio label="1">是</el-radio>
            <el-radio label="2">否</el-radio>
          </el-radio-group>
        </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>
  </div>



</template>
