<!--用户选择框-->
<template>
  <div style="width: 100%">
    <BasicModal
      v-bind="$attrs"
      @register="register"
      :title="modalTitle"
      width="65%"
      :height="500"
      wrapClassName="j-user-select-modal"
      @ok="handleOk"
      destroyOnClose
      @visible-change="visibleChange"
    >
      <a-row>
        <a-col :span="showSelected ? 18 : 24">
          <a-form :model="searchModel" :label-col="labelCol" :wrapper-col="wrapperCol">
            <a-row :gutter="24">
              <a-col :lg="18">
                <a-row :gutter="24">
                  <a-col>
                    <a-form-item label="标签名称">
                      <JInput placeholder="请输入" v-model:value="searchModel.lableName" :allowClear="true" />
                    </a-form-item>
                  </a-col>
                </a-row>
                <a-row :gutter="24">
                  <a-col :span="12">
                    <a-form-item
                      label="一级分类"
                      :labelCol="{ xs: { span: 24 }, sm: { span: 8 } }"
                      :wrapperCol="{ xs: { span: 24 }, sm: { span: 16 } }"
                    >
                      <JSearchSelect
                        placeholder="请输入"
                        v-model:value="searchModel.pclassifyCode"
                        :allowClear="true"
                        dict="st_classify,classify_name,classify_code,level1='1' and has_child='1' order by sort_no desc"
                        @change="fSelectChange"
                      />
                    </a-form-item>
                  </a-col>
                  <a-col :span="12">
                    <a-form-item
                      label="二级分类"
                      :labelCol="{ xs: { span: 24 }, sm: { span: 8 } }"
                      :wrapperCol="{ xs: { span: 24 }, sm: { span: 16 } }"
                    >
                      <JSearchSelect
                        placeholder="请输入"
                        v-model:value="searchModel.sclassifyCode"
                        :allowClear="true"
                        :dict="sDict"
                        @click="sSelectClick"
                      />
                    </a-form-item>
                  </a-col>
                </a-row>
              </a-col>
              <a-col :span="3">
                <a-button style="width: 100%; height: 80%; line-height: 50%" type="primary" @click="handlerSearch">查询</a-button>
              </a-col>
              <a-col :span="3">
                <a-button style="width: 100%; height: 80%; line-height: 50%" type="primary" @click="handleAdd"> 新建</a-button>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="24" :pull="1">
                <a-form-item label="已选信息">
                  <a-tag v-for="(item, i) in selectTag" :key="item.lableCode" closable @close="handlerTagClose(item)">{{ item.lableName }}</a-tag>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="24" :pull="1">
                <a-form-item label="查询结果">
                  <BasicTable
                    ref="tableRef"
                    :columns="columns"
                    :scroll="tableScroll"
                    v-bind="getBindValue"
                    :useSearchForm="false"
                    :formConfig="formConfig"
                    :api="list"
                    :height="100"
                    :searchInfo="searchInfo"
                    :showIndexColumn="false"
                    :rowSelection="rowSelection"
                    :beforeFetch="
                      (params) => {
                        params = Object.assign(params, { column: 'updatedTime', order: 'desc' });
                      }
                    "
                    :indexColumnProps="indexColumnProps"
                    :pagination="{ showQuickJumper: false, pageSizeOptions: [5, 10, 15, 20, 30] }"
                  >
                    <!-- update-begin-author:taoyan date:2022-5-25 for: VUEN-1112一对多 用户选择 未显示选择条数，及清空 -->
                    <template #tableTitle> </template>
                    <!-- update-end-author:taoyan date:2022-5-25 for: VUEN-1112一对多 用户选择 未显示选择条数，及清空 -->
                  </BasicTable>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-col :span="showSelected ? 6 : 0">
          <BasicTable
            v-bind="selectedTable"
            :dataSource="selectRows"
            :scroll="tableScroll"
            :useSearchForm="false"
            :showIndexColumn="false"
            :height="100"
            :formConfig="{ showActionButtonGroup: false, baseRowStyle: { minHeight: '40px' } }"
          >
            <!--操作栏-->
            <template #action="{ record }">
              <a href="javascript:void(0)" @click="handleDeleteSelected(record)"><Icon icon="ant-design:delete-outlined" /></a>
            </template>
          </BasicTable>
        </a-col>
      </a-row>
    </BasicModal>
    <StLableModal @register="registerModal" @success="handleSuccess" />
  </div>
</template>
<script lang="ts">
  import { message } from 'ant-design-vue';
  import { defineComponent, ref, toRaw, unref, watch } from 'vue';
  import { JInput, JSearchSelect } from '/@/components/Form';
  import { useTagSelectBiz } from '/@/components/Form/src/jeecg/hooks/useTagSelectBiz';
  import { selectProps } from '/@/components/Form/src/jeecg/props/props';
  import { BasicModal, useModal, useModalInner } from '/@/components/Modal';
  import { useAttrs } from '/@/hooks/core/useAttrs';
  import { createAsyncComponent } from '/@/utils/factory/createAsyncComponent';
  import { list } from '/@/views/standardlib/base/StLable.api';
  import StLableModal from '/@/views/standardlib/base/components/StLableModal.vue';

  export default defineComponent({
    name: 'UserSelectModal',
    components: {
      //此处需要异步加载BasicTable
      JInput,
      JSearchSelect,
      BasicModal,
      StLableModal,
      BasicTable: createAsyncComponent(() => import('/@/components/Table/src/BasicTable.vue'), {
        loading: true,
      }),
    },
    props: {
      ...selectProps,
      //选择框标题
      modalTitle: {
        type: String,
        default: '选择用户',
      },
    },
    emits: ['register', 'getSelectResult'],
    setup(props, { emit, refs }) {
      // update-begin-author:taoyan date:2022-5-24 for: VUEN-1086 【移动端】用户选择 查询按钮 效果不好 列表展示没有滚动条
      const tableScroll = ref<any>({ x: false });
      const tableRef = ref();
      //注册弹框
      const [register, { closeModal }] = useModalInner(() => {
        if (window.innerWidth < 900) {
          tableScroll.value = { y: 200 };
        } else {
          tableScroll.value = { x: false, y: 200 };
        }
        //update-begin-author:taoyan date:2022-6-2 for: VUEN-1112 一对多 用户选择 未显示选择条数，及清空
        setTimeout(() => {
          if (tableRef.value) {
            tableRef.value.setSelectedRowKeys(selectValues['value'] || []);
          }
        }, 800);
        //update-end-author:taoyan date:2022-6-2 for: VUEN-1112 一对多 用户选择 未显示选择条数，及清空
      });
      // update-end-author:taoyan date:2022-5-24 for: VUEN-1086 【移动端】用户选择 查询按钮 效果不好 列表展示没有滚动条
      const attrs = useAttrs();
      //表格配置
      const config = {
        canResize: false,
        bordered: true,
        size: 'small',
      };
      const [registerModal, { openModal }] = useModal();
      const getBindValue = Object.assign({}, unref(props), unref(attrs), config);
      const [{ rowSelection, visibleChange, selectValues, indexColumnProps, getSelectResult, handleDeleteSelected, selectRows, checkedKeys }] =
        useTagSelectBiz(list, getBindValue);
      const searchInfo = ref(props.params);
      //查询form
      const formConfig = {
        // baseColProps: {
        //   xs: 24,
        //   sm: 8,
        //   md: 6,
        //   lg: 8,
        //   xl: 6,
        //   xxl: 6,
        // },
        // //update-begin-author:taoyan date:2022-5-24 for: VUEN-1086 【移动端】用户选择 查询按钮 效果不好 列表展示没有滚动条---查询表单按钮的栅格布局和表单的保持一致
        // actionColOptions: {
        //   xs: 24,
        //   sm: 8,
        //   md: 8,
        //   lg: 8,
        //   xl: 8,
        //   xxl: 8,
        // },
        //update-end-author:taoyan date:2022-5-24 for: VUEN-1086 【移动端】用户选择 查询按钮 效果不好 列表展示没有滚动条---查询表单按钮的栅格布局和表单的保持一致
        schemas: [
          {
            label: '标签名称',
            field: 'lableName',
            component: 'JInput',
          },
          {
            label: '一级分类',
            field: 'pclassifyCode',
            component: 'JInput',
          },
          {
            label: '二级分类',
            field: 'sclassifyCode',
            component: 'JInput',
          },
        ],
      };
      //定义表格列
      const columns = [
        {
          title: '标签代码',
          dataIndex: 'lableCode',
          width: 60,
          align: 'left',
          ifShow: true,
        },
        {
          title: '标签名称',
          dataIndex: 'lableName',
          width: 220,
          align: 'left',
          resizeable: true,
        },
      ];
      const searchModel = {
        lableName: '',
        pclassifyCode: '',
        sclassifyCode: '',
      };
      const labelCol = ref({
        xs: { span: 24 },
        sm: { span: 4 },
      });
      const wrapperCol = ref({
        xs: { span: 24 },
        sm: { span: 20 },
      });
      //已选择的table信息
      const selectedTable = {
        pagination: false,
        showIndexColumn: false,
        scroll: { y: 200 },
        size: 'small',
        canResize: true,
        bordered: true,
        rowKey: 'lableCode',
        columns: [
          {
            title: '标签名称',
            dataIndex: 'lableName',
            width: 250,
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            width: 40,
            slots: { customRender: 'action' },
          },
        ],
      };
      const sDict = ref('');
      function fSelectChange(val) {
        let dit = "st_classify,classify_name,classify_code,level1='2' and upper_classify_code='" + val + "' order by sort_no desc";
        sDict.value = dit;
      }
      function sSelectClick() {
        if (!searchModel.pclassifyCode) {
          message.warning('请先选择一级分类!');
        }
      }
      function handleAdd() {
        openModal(true, {
          isUpdate: false,
          showFooter: true,
        });
      }
      function handleSuccess() {
        const tableAction = unref(tableRef);
        tableAction.setProps({ searchInfo: toRaw(searchModel) });
        tableAction.reload();
      }
      /**
       * 确定选择
       */
      function handleOk() {
        getSelectResult((options, values) => {
          //回传选项和已选择的值
          emit('getSelectResult', options, values);
          //关闭弹窗
          closeModal();
        });
      }
      function handlerSearch() {
        const tableAction = unref(tableRef);
        tableAction.setProps({ searchInfo: toRaw(searchModel) });
        tableAction.reload();
      }
      const selectTag = ref<Array<Object>>([]);
      function handlerTagClose(record) {
        handleDeleteSelected(record);
      }
      watch(
        selectRows,
        () => {
          // let data = tableRef.value.getSelectRows()
          // data.forEach(elem => {
          //   if(checkedKeys.value.indexOf(elem.lableCode)>-1){
          //   allData.push({lableCode:elem.lableCode,lableName:elem.lableName})
          //   }
          // });
          let params = {};
          params[props.rowKey] = checkedKeys.value.join(',');
          params['pageSize'] = checkedKeys.value.length;
          if (params['pageSize'] > 0) {
            list(params).then((rep) => {
              let allData = Array<Object>(params['pageSize']);
              rep.records.forEach((item) => {
                let index = checkedKeys.value.indexOf(item.lableCode);
                allData[index] = item;
              });
              selectTag.value = allData;
            });
          } else {
            selectTag.value = [];
          }
        },
        { immediate: true }
      );
      const showSelected = ref(false);
      return {
        //config,
        searchModel,
        labelCol,
        wrapperCol,
        handleOk,
        searchInfo,
        register,
        indexColumnProps,
        visibleChange,
        getBindValue,
        list,
        formConfig,
        columns,
        rowSelection,
        selectRows,
        checkedKeys,
        selectedTable,
        handleDeleteSelected,
        tableScroll,
        tableRef,
        handlerSearch,
        sDict,
        fSelectChange,
        sSelectClick,
        showSelected,
        handleAdd,
        handleSuccess,
        registerModal,
        handlerTagClose,
        selectTag,
      };
    },
  });
</script>
