<template>
  <div>
    <div class="jeecg-basic-table-form-container" @keyup.enter="searchQuery">
        <a-form :model="queryParam" :label-col="labelCol" :wrapper-col="wrapperCol">
          <a-row :gutter="24">
            <a-col :lg="6">
                    <a-form-item :label="searchFormSchema[0].label">
                        <JInput placeholder="请输入" v-model:value="queryParam[searchFormSchema[0].field]"></JInput>
                    </a-form-item>
                </a-col>
                 <a-col :lg="6">
                     <a-form-item :label="searchFormSchema[1].label">
                         <!--<JSearchSelect  placeholder="请选择" :allowClear="true" v-model:value="queryParam[searchFormSchema[1].field]" dict="st_domain,domain_name,domain_code"></JSearchSelect>-->
                         <JTreeSelectDomain  placeholder="请选择" :allowClear="true" 
                            v-model:value="queryParam[searchFormSchema[1].field]" 
                            dict="st_domain,domain_name,domain_code" 
                            pidField="upper_domain_code"
                            pidValue="0"
                            hasChildField="has_child"
                            ></JTreeSelectDomain>
                        </a-form-item>
                 </a-col>
                 <a-col :lg="6">
                     <a-form-item :label="searchFormSchema[2].label">
                        <StSelectLable :value="queryParam.lableCodes" :allowClear="true" @change="updateSelectLable" />
                     </a-form-item>
                 </a-col>
                 <a-col :lg="6">
                    <a-form-item>
                      <a-space :size="5">
                        <a-button type="link" style="padding:0px" @click="expand = !expand">
                            <template v-if="expand">
                              收缩<UpOutlined style="margin-left:0px"/>
                            </template>
                            <template v-else>
                              展开<DownOutlined style="margin-left:0px"/>
                            </template>
                        </a-button>
                        <a-button type="primary" preIcon="ant-design:search-outlined" @click="searchQuery" >查询</a-button>
                        <a-button type="primary" preIcon="ant-design:reload-outlined" @click="searchReset" >重置</a-button>
                      </a-space>
                    </a-form-item>
                 </a-col>
            </a-row>
           <ClassifyCheckbox ref="checkBoxRef" v-show="expand"/>
        </a-form>

    <!--引用表格-->
   <BasicTable @register="registerTable" :rowSelection="rowSelection" @fetch-success="fetchCallBack">
     <!--插槽:table标题-->
      <template #tableTitle>
          <a-button type="primary" @click="handleAdd" preIcon="ant-design:plus-outlined" v-if="hasPermission('act.main:st_ca_main:add')">新建</a-button>
          <a-button  v-show="showUpBtn" type="primary" preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button>
          <j-upload-button  v-show="showUpBtn" type="primary" preIcon="ant-design:import-outlined" @click="onImportXls">导入</j-upload-button>
          <a-dropdown v-if="selectedRowKeys.length > 0 && showUpBtn" >
              <template #overlay>
                <a-menu>
                  <a-menu-item key="1" @click="batchHandleDelete">
                    <Icon icon="ant-design:delete-outlined"></Icon>
                    删除
                  </a-menu-item>
                </a-menu>
              </template>
              <a-button>批量操作
                <Icon icon="mdi:chevron-down"></Icon>
              </a-button>
        </a-dropdown>
        <a-button @click="joinCheckHandler" v-if="hasPermission('act.main:st_ca_main:add')">加入检查</a-button>
        <a-button v-show="showUpBtn" class="check-btn">待检查项[3]</a-button>
      </template>
       <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)"/>
      </template>
      <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'lableNameList' && record.lableNameList &&record.lableNameList.length>0">
            <JTagsFormat style="cursor: pointer;" :value="record.lableNameList" :code="record.lableCodeList" :length="3" :strLen="14" @searchByLable="searchByLable"/>
          </template>
      </template>
      <!--字段回显插槽-->
      <template #htmlSlot="{text}">
         <div v-html="text"></div>
      </template>
      <!--省市区字段回显插槽-->
      <template #pcaSlot="{text}">
         {{ getAreaTextByCode(text) }}
      </template>
      <template #fileSlot="{text}">
         <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
         <a-button v-else :ghost="true" type="primary" preIcon="ant-design:download-outlined" size="small" @click="downloadFile(text)">下载</a-button>
      </template>
    </BasicTable>
    <div class="table-col-detail" v-show="otherParam.tbshow">
       <StCaMainTabs :actInfo="otherParam.record" ref="tabsRef" />
    </div>
  </div>
    <!-- 表单区域 -->
    
  </div>
  <StCaMainModal @register="registerModal" @success="handleSuccess"></StCaMainModal>
  <JoinCheckModal @register="registerJCModal" @success="handleSuccess"/>
</template>

<script lang="ts" name="standardlib-controlactivity-StCaMainList" setup>
import { DownOutlined, UpOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { onMounted, reactive, ref, toRaw, unref } from 'vue';
import { useRoute } from 'vue-router';
import JTagsFormat from '../components/JTagsFormat.vue';
import { batchDelete, deleteOne, getExportUrl, getImportUrl, list } from './StCaMain.api';
import { columns, searchFormSchema } from './StCaMain.data';
import StCaMainModal from './components/StCaMainModal.vue';
import StCaMainTabs from './components/StCaMainTabs.vue';
import { JInput, JTreeSelectDomain, StSelectLable } from '/@/components/Form';
import { useModal } from '/@/components/Modal';
import { BasicTable, TableAction } from '/@/components/Table';
import { useListPage } from '/@/hooks/system/useListPage';
import { downloadFile } from '/@/utils/common/renderUtils';
import ClassifyCheckbox from '/@/views/standardlib/components/ClassifyCheckbox.vue';
import JoinCheckModal from '/@/views/standardlib/components/JoinCheckModal.vue';
import { usePermission } from '/@/hooks/web/usePermission';
const { hasPermission } = usePermission();

  const expand = ref(false);
  const checkBoxRef = ref(null)
  const route = useRoute();
  const showUpBtn = ref(false)
  const restFlag = ref(false)
  const checkedKeys = ref<Array<string | number>>([]);
  const tabsRef = ref(null)
  const otherParam = reactive({
    id: null,
    tbshow: false,
    record: {}
  })
  //注册model
  const [registerModal, {openModal}] = useModal();
  const [registerJCModal, {openModal:openModalJC}] = useModal();
  //注册table数据
  const { prefixCls,tableContext,onExportXls,onImportXls } = useListPage({
      tableProps:{
           title: '控制活动',
           api: list,
           columns,
           canResize:false,
           useSearchForm: false,
          //  formConfig: {
          //     //labelWidth: 120,
          //     schemas: searchFormSchema,
          //     autoSubmitOnEnter:true,
          //     showAdvancedButton:true,
          //     fieldMapToNumber: [
          //     ],
          //     fieldMapToTime: [
          //     ],
          //   },
           actionColumn: {
               width: 160
            },
            showTableSetting: false,
            beforeFetch(params) {
              params = Object.assign(params,{ column: 'updatedTime', order: 'desc'})
            },
            customRow: (record, _index) =>{
              return {
                onClick: (event) => {
    
                    if(event.target.localName!="tr" && event.target.parentNode.localName!="tr"){
                      return
                    }
                    // 清楚所有样式
                    let oldList = document.querySelectorAll(".ant-table-row-selected")
                    if(oldList){
                        for (let j = 0; j < oldList.length; j++) {
                            oldList[j].classList.remove("ant-table-row-selected")
                        }
                    }
                    // 如果是true 并且 id相同就影藏下方管理的信息
                    if(otherParam.tbshow && record.id ===  otherParam.id){
                      otherParam.tbshow = false
                      return 
                    }
                    otherParam.tbshow = true
                    otherParam.id = record.id
                    otherParam.record = record
                    let node = event.target;
                    if(node.localName!="tr"){
                      node = event.target.parentNode
                    }
                    //console.log(node.getAttribute('data-row-key'))
                    node.classList.add("ant-table-row-selected")
                    tabsRef.value?.initActiveKey()
                },
              };
            }
      },
       exportConfig: {
            name:"控制活动",
            url: getExportUrl,
          },
          importConfig: {
            url: getImportUrl,
            success: handleSuccess
          },
  })
  const [registerTable, {setProps,reload},{ rowSelection, selectedRowKeys }] = tableContext
//-----自定义查询----begin--------
onMounted(()=>{
  const bizNo = toRaw(route.query).bizNo
  const lableCodes = toRaw(route.query).lableCode
  if(!!bizNo){
  // const queryName = toRaw(route.query).bizNo
    setProps({searchInfo:{caNo:bizNo}});
    reload()
  }

  if(!!lableCodes){
    queryParam.lableCodes = [];
    queryParam.lableCodes.push(lableCodes);
    setProps({searchInfo:{lableCodes:[lableCodes]}});
    reload()
  }
})
function fetchCallBack(data){

  console.log("--call--")
  console.log(restFlag.value)
  const bizNo = toRaw(route.query).bizNo
  if(!!bizNo && !restFlag.value){
  //  ?.click()
  let nodes = document.querySelectorAll(".ant-table-row");
  console.log(nodes)
  if(nodes && nodes.length >0){
    let node = nodes[0]
    //node.classList.add("ant-table-row-selected")
    node.click()
  }
  }
  console.log("--call--")
}
const labelCol = reactive({
  xs: {span: 24},
  sm: {span: 8},
})
const wrapperCol = reactive({
    xs: {span: 24},
    sm: {span: 16},
})
const queryParam = reactive({
  lableCodes:[]
});
function initParam() {
  const schemas = unref(searchFormSchema);
  schemas.forEach((item) => {
    queryParam[item.field] = ''
  });
  queryParam['checkClassFiy'] = null
  queryParam['lableCodes'] = []
}
initParam()
function searchQuery(){
    restFlag.value = true
    if(expand.value){
      let checkData = checkBoxRef.value?.getCheckValue()
      if(checkData){
        queryParam['checkClassFiy'] = checkData
      }
    }
    otherParam.tbshow = false
    let oldList = document.querySelectorAll(".ant-table-row-selected")
    if(oldList){
        for (let j = 0; j < oldList.length; j++) {
            oldList[j].classList.remove("ant-table-row-selected")
        }
    }
    setProps({searchInfo:toRaw(queryParam)});
    reload()
}
function searchReset(){
    otherParam.tbshow = false
    let oldList = document.querySelectorAll(".ant-table-row-selected")
    if(oldList){
        for (let j = 0; j < oldList.length; j++) {
            oldList[j].classList.remove("ant-table-row-selected")
        }
    }
    //Object.assign(queryParam,{ name: '',age_begin: '',age_end: '',sex: '',id: ''});
    initParam()
    const bizNo = toRaw(route.query).bizNo
    if(!!bizNo){
      setProps({searchInfo:{caNo:null}});
    }

    
    checkBoxRef.value?.initQueryParam()
    restFlag.value = true
    reload();
}
//自定义查询----end--------- 
function getTagColor(index){
  let colorArr = ['red','orange','green','pink','cyan','blue','purple']
  let i = index%colorArr.length
  return colorArr[i]
}

function updateSelectLable(val){
  console.log(val)
  queryParam.lableCodes = val
}
function joinCheckHandler(){
  let caNos = selectedRowKeys.value
  if(!caNos||caNos.length==0){
    message.warning('请选择控制活动！');
    return;
  }
  openModalJC(true, {
       record: {caNos:caNos,type:'camain'},
       isUpdate: false,
       showFooter: true,
     });
}
   /**
    * 新增事件
    */
  function handleAdd() {
     openModal(true, {
       isUpdate: false,
       showFooter: true,
     });
  }
   /**
    * 编辑事件
    */
  function handleEdit(record: Recordable) {
     openModal(true, {
       record,
       isUpdate: true,
       showFooter: true,
     });
   }
   /**
    * 详情
   */
  function handleDetail(record: Recordable) {
     openModal(true, {
       record,
       isUpdate: true,
       showFooter: false,
     });
   }
   /**
    * 删除事件
    */
  async function handleDelete(record) {
     await deleteOne({id: record.id}, handleSuccess);
   }
   /**
    * 批量删除事件
    */
  async function batchHandleDelete() {
     await batchDelete({ids: selectedRowKeys.value}, handleSuccess);
   }
   /**
    * 成功回调
    */
  function handleSuccess() {
      (selectedRowKeys.value = []) && reload();
   }
   /**
      * 操作栏
      */
  function getTableAction(record){
       return [
        {
           label: '删除',
           color: 'error',
           popConfirm: {
             title: '你确定要删除选中的控制活动吗？',
             confirm: handleDelete.bind(null, record),
           },
           disabled:!hasPermission('act.main:st_ca_main:delete')
         },
         {
           label: '修改',
           onClick: handleEdit.bind(null, record),
           disabled:!hasPermission('act.main:st_ca_main:edit')
         },
         {
           label: '详情',
           onClick: handleDetail.bind(null, record),
         },
       ]
   }
     /**
        * 下拉操作栏
        */
  function getDropDownAction(record){
       return []
  }
  function searchByLable(lableCode,lableName) {
    queryParam.lableCodes = [];
    queryParam.lableCodes.push(lableCode);
    setProps({searchInfo:{lableCodes:[lableCode]}});
    reload()
  }


</script>

<style scoped>
.check-btn{
  position: absolute;
  right: 0px;
}
.table-col-detail {
    border-top: 10px solid #f0f2f5;
    background-color: #ffffff;
    padding-left: 20px;
    padding-right: 20px;
  }
</style>