<template>
  <div class="page-content">
    <jy-table
      ref="tableRef"
      :listData="dataList"
      :rowKey="rowKey"
      :listCount="dataCount"
      @sort-change="handleSortChange"
      v-bind="contentTableConfig"
      v-model:page="pageInfo"
    >
      <!-- 1.header中的插槽 -->
      <template #headerHandler>
        <el-button v-if="isCreate" type="primary" size="default" @click="handleNewClick">
          {{ buttons[0] }}
        </el-button>
        <el-button v-if="isExport" type="primary" size="default" @click="handleExportClick">
          {{ buttons[1] }}
        </el-button>
        <slot name="otherHandler"></slot>
      </template>
      
      <!-- 2.列中的插槽 -->
      <template #handler="scope">
        <div class="handle-btns">
          <el-button
            v-if="isUpdate && showHandler('edit', scope.row)"
            icon="Edit"
            size="small"
            type="primary"
            link
            @click="handleEditClick(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            v-if="isDelete && showHandler('delete', scope.row)"
            icon="Delete"
            size="small"
            type="primary"
            link
            @click="handleDeleteClick(scope.row)"
            >
            删除
          </el-button>
        </div>
      </template>
      
      <template #handlerImportExport="scope">
        <div class="handle-btns">
          <el-button
            v-if="isUpdate"
            icon="Edit"
            size="small"
            type="primary"
            link
            @click="handleExportSingleClick(scope.row)"
          >
            导出
          </el-button>
        </div>
      </template>

      <!-- 录音插槽 -->
      <template #audioPlayerHandler="scope">
        <el-button
          v-if="scope.row.recordPath"
          icon="Microphone"
          size="small"
          type="primary"
          link
          @click="handleAudioView(scope.row)"
          >录音</el-button
        >
      </template>
      <!-- 号码点击呼叫插槽 -->
      <template #recordCallHandler="scope">
        <el-tag class="ml-2" @click="handleRecordCall(scope.row)">
          <!-- getOfffixNuber(scope.row.callType==1 ? scope.row.caller : scope.row.callee) -->
          {{
            getOfffixNuber(scope.row.callType==1 ? scope.row.caller : scope.row.callee)
          }}
        </el-tag>
      </template>

      <!-- 在page-content中动态插入剩余的插槽 -->
      <template v-for="item in otherPropSlots" #[item.slotName]="scope">
        <template v-if="item.slotName">
          <template v-if="item.slotName==='handler'">
              <el-button
                v-if="isUpdate"
                icon="Edit"
                size="small"
                type="primary"
                link
                @click="handleEditClick(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                v-if="isDelete"
                icon="Delete"
                size="small"
                type="primary"
                link
                @click="handleDeleteClick(scope.row)"
                >删除</el-button
              >
          </template>
          <slot :name="item.slotName" :row="scope.row" :options="item"></slot>

        </template>
      </template>
    </jy-table>
  </div>
</template>

<script>
  import { defineComponent, ref, toRefs, computed, watch, getCurrentInstance } from 'vue';
  import useSystemStore from '@/store/main/system/system';
  import JyTable from '@/base-ui/table';
  import { getUnprefixNuber,getOfffixNuber } from '@/utils/index';
  export default defineComponent({
    name: 'pageContent',
    components: {
      JyTable,
    },
    props: {
      contentTableConfig: {
        type: Object,
        require: true,
      },
      initParams:{
        type: Object,
      },
      pageName: {
        type: String,
        required: true,
      },
      rowKey: {
        type: String,
        required: '',
      },
      isDelete: {
        type: Boolean,
        default: true,
      },
      isCreate: {
        type: Boolean,
        default: true,
      },
      isExport: {
        type: Boolean,
        default: true,
      },
      buttons: {
        type: Array,
        default: ['新建', '导出'],
      },
      isUpdate: {
        type: Boolean,
        default: true,
      },
      query: {
        // 默认参数
        type: Object,
        default: null,
      },
    },
    emits: [
      'newBtnClick',
      'editBtnClick',
      'delBtnClick',
      'viewBtnClick',
      'audioViewBtnClick',
      'recordCallBtnClick',
      'resetPassBtnClick',
      'allotRoleBtnClick',
      'dataPowerBtnClick',
      'assignUserBtnClick',
      'recordOrderBtnClick',
      'sort-change',
    ],
    setup(props, { emit }) {
      // 0.获取操作的权限
      // const isCreate = usePermission(props.pageName, 'create')
      // const isUpdate = usePermission(props.pageName, 'update')
      // const isDelete = usePermission(props.pageName, 'delete')
      // const isQuery = usePermission(props.pageName, 'query')
      const isCreate = props.isCreate;
      const isExport = props.isExport ?? true;
      const isUpdate = props.isUpdate;
      const buttons = ref(props.buttons);
      const isDelete = props.isDelete;

      const open = ref(false);
      const data = reactive({ form: {} });
      const tableRef = ref();
      const { form } = toRefs(data);
      const { proxy } = getCurrentInstance();
      // 1.双向绑定pageInfo
      let pageInfo = ref({ currentPage: 1, pageSize: 10 });
      isExport
      
      watch(pageInfo, (e) => {
        console.log('watch',e)
        getPageData(searchParams.value);
        
      });
      onActivated(() => {
        if (!useSystemStore().pageFlag || !props.initParams) {
          console.log('pageFlag', props.initParams, searchParams.value);
          getPageData(searchParams.value || props.initParams);
        }
      });
      onMounted(() => {
        if (useSystemStore().pageFlag) {
          useSystemStore().setPageFlag(false);
          console.log('useSystemStore().pageFlag',useSystemStore().pageFlag)
          if (props.initParams) {
            getPageData(props.initParams);
          }else{
            getPageData();
          }
          
        }
       
      });
      const searchParams = ref();

      function getPageData(queryInfo, sort = {}) {
        if (Object.keys(sort).length === 0) {
          tableRef.value.clearSort();
        }
        console.log('getPageData', queryInfo, sort);
        if (!props.contentTableConfig.subimitLoding && props.pageName) {
          searchParams.value = queryInfo;
          
          if (props.query)
            searchParams.value = {
              ...searchParams.value,
              ...props.query,
            };
          useSystemStore().getPageListAction({
            pageName: props.pageName,
            
            queryInfo: {
              pageNum: pageInfo.value.currentPage,
              pageSize: pageInfo.value.pageSize,
              ...searchParams.value,
              ...sort,
            },
          });
        }
      }
      // 3.从vuex中获取数据
      let dataList = ref([]);
      let dataCount = ref(0);
      if (props.contentTableConfig.customData) {
        dataList.value = props.listData?.list;
        dataCount.value = props.listData?.total;
      } else {
        dataList = computed(() => useSystemStore().listData);
        dataCount = computed(() => useSystemStore().dataCount);
      }

      function setPageData(total, list) {
        dataList.value = list;
        dataCount.value = total;
      }

      // if(props.pageName == '/system/dept'){
      //   dataList.value = []
      //   dataList.value = computed(() => useSystemStore().treelistData)
      // }

      // 4.获取其他的动态插槽名称
      const otherPropSlots = props.contentTableConfig?.propList.filter((item) => {
        // if (item.slotName === "handler") return true;
        // return false
        return item.customSlot;
      });

      // 5.删除/编辑/新建操作
      const handleDeleteClick = (item) => {
        let idName = props.rowKey;
        if (!idName)
          idName = props.pageName.split('/')[props.pageName.split('/').length - 1] + 'Id';
        proxy.$modal
          .confirm('确认删除此条数据吗？')
          .then(() => {
            useSystemStore()
              .deletePageDataAction({
                pageName: props.pageName,
                id: item[idName],
                subimitLoding: props.contentTableConfig.subimitLoding,
              })
              .then(() => {
                pageInfo.value = { currentPage: 1, pageSize: 10 };
                emit('delBtnClick', item[idName]);
              });
          })
          .catch(() => {});
      };
      const handleExportClick = () => {
        const fileName = `${props.contentTableConfig.title ?? '文件'}-${new Date().getTime()}.xlsx`;

        proxy.download(props.pageName + '/exportExcel', searchParams.value || {}, fileName);
      };
      const handleExportSingleClick = (item) => {
        emit('exportBtnClick', item);
      };

      const handleNewClick = () => {
        emit('newBtnClick', { pageInfo: pageInfo.value });
      };
      const handleEditClick = (item) => {
        emit('editBtnClick', item, { pageInfo: pageInfo.value });
      };
      const handleAudioView = (item) => {
        emit('audioViewBtnClick', item);
      };
      const handleRecordCall = (item) => {
        emit('recordCallBtnClick', item);
      };
      const handleSortChange = ({sortInfo}) => {
        console.log('sortInfo', sortInfo, props.contentTableConfig.propList);
        const orderField = props.contentTableConfig.propList.find((item) => item.prop === sortInfo.prop && item.sortable === 'custom');
        console.log('orderField', orderField);
        if (orderField && sortInfo.order) {
          let val = sortInfo.order === 'ascending' ? orderField.sortableOptions.order
          [0] : orderField.sortableOptions.order[1];
          const sortDetail = {};
          sortDetail[`${orderField.sortableOptions.fileld}`] = val;
          getPageData(searchParams.value, sortDetail);
        }
        // emit('sort-change', sortInfo);
      };

      // 操作中按钮显示控制
      const showHandler = (name, row) => {
        if (props.contentTableConfig.handlerShow && typeof props.contentTableConfig.handlerShow === 'function') {
          return props.contentTableConfig.handlerShow(name, row);
        }
        return true;
      }

      return {
        showHandler,
        tableRef,
        getSelectionRows: () => {
          return tableRef.value.getSelectionRows()
        },
        handleSortChange,
        setPageData,
        getOfffixNuber,
        getUnprefixNuber,
        pageInfo,
        getPageData,
        otherPropSlots,
        isCreate,
        isExport,
        isUpdate,
        isDelete,
        dataList,
        dataCount,
        open,
        form,
        handleDeleteClick,
        handleNewClick,
        handleEditClick,
        handleExportClick,
        handleExportSingleClick,
        handleAudioView,
        handleRecordCall,
      };
    },
  });
</script>

<style scoped>
  /* .page-content {} */
</style>
