<template>
  <div class="main-content main-content-padding">
    <h-card class="margin-bottom list-query-form">
      <h-b-form ref="formRef" name="use" id="query-config-form" v-bind="props" :is-query="false">
        <template #header>
          <p class="card-title">
            <span style="font-size: 18px; font-weight: 550">
              {{ t('queryConfiguration.configCreate.form.title') }}
            </span>
          </p>
        </template>
      </h-b-form>
    </h-card>
    <h-card class="list-table" style="margin-bottom: 50px">
      <div class="top">
        <p class="card-title">
          <span style="font-size: 18px; font-weight: 550">SQL</span>
        </p>
        <h-divider></h-divider>
        <h-textarea
          style="font-size: 18px; font-weight: 550; color: #909090"
          v-model:value="sqlValue"
          :rows="13"
          :disabled="true"
          size="large"
        />
      </div>
    </h-card>
    <div class="permission-pllicy-btn">
      <h-button type="primary" @click="closePage">{{ t('platform.common.close') }}</h-button>
    </div>
    <search-auth-model
      ref="SearchAuthModelRef"
      @searchAuthModelFunSuccess="searchAuthModelFunSuccess"
    ></search-auth-model>
  </div>
</template>
<script lang="ts">
import { useForm } from '@crami/bui-platform';
import { defineComponent, ref, reactive, watch, onBeforeMount } from 'vue';
import { useHttp } from '@crami/http';
import { cloneDeep } from 'lodash-es';
import { useI18n } from '@crami/locale';
import SearchAuthModel from './Components/SearchAuthModel.vue';

import { useMultiTab } from '@/components/multi-tab';

export default defineComponent({
  name: 'SystemBuiltIn',
  components: { SearchAuthModel },
  props: {
    // propsData: {
    //   type: Object,
    //   default: () => {
    //     return {};
    //   },
    // },
    config_eid: {
      type: String,
    },
    disabled: {
      type: Boolean,
      return: false,
    },
  },

  setup(_) {
    const { t } = useI18n();
    const [{ close }] = useMultiTab();
    const dataPermissionVO = ref({});
    // 查询权限
    const SearchAuthModelRef = ref(null);
    const queryPermissions = ref([]);
    const loading = ref(false);

    const schemasBasic: {
      dataIndex?: string;
      title?: string;
      valueType?: string;
      width?: string;
      fieldProps?: unknown;
      formItemProps?: unknown;
    }[] = reactive([
      {
        dataIndex: 'name',
        title: t('queryConfiguration.configCreate.form.name'),
        valueType: 'Input',
        width: '25%',
        fieldProps: {
          placeholder: t('permission.common.inputPlaceholder'),
          disabled: true,
        },
        formItemProps: {
          labelCol: { span: 8 },
          wrapperCol: { span: 18 },
          rules: [
            {
              pattern: '^([\\s\\S]{0,25})?$',
              message: '请输入25个字符以内',
              trigger: 'change',
            },
            {
              message: '请输入名称',
              pattern: '^\\s*(\\S+\\s*)+$',
              required: true,
              trigger: 'change',
            },
          ],
        },
      },
      {
        dataIndex: 'queryPermissions',
        title: t('queryConfiguration.configCreate.form.queryPermissions'),
        valueType: 'Select',
        width: '25%',
        formItemProps: {
          labelCol: { span: 8 },
          wrapperCol: { span: 21 },
        },
        fieldProps: {
          placeholder: t('permission.common.selectPlaceholder'),
          mode: 'multiple',
          showSearch: false,
          options: [],
          notFoundContent: null,
          open: false,
          class: 'permission-pllicy-select-sub',
          // maxTagTextLength: 3,
          // maxTagCount: 3,
          disabled: _.disabled,
          onClick: () => {
            if (_?.config_eid) {
              SearchAuthModelRef.value?.show({
                EID: _?.config_eid,
                ENAME: methodsMain.getData().name,
              });
            }
          },
        },
      },
    ]);
    const [formRef, props, methodsMain] = useForm(
      {
        beforeSetData: (type, props) => {
          if (type === 'config') {
            const _props: any = {
              submitter: {
                isQuery: true,
                showResetButton: false,
                showSubmitButton: false,
                showAdvancedButton: false,
                showActionButtonGroup: false,
              },
              autoSubmitOnEnter: true,
              column: 4,
              // layout: 'vertical',
              labelCol: { span: 8 }, //标签
              wrapperCol: { span: 20 },
              title: '',
              schemas: cloneDeep(schemasBasic),
            };
            methodsMain?.setProps(_props, props);
            methodsMain.updateSchema(
              [
                {
                  dataIndex: 'queryPermissions',
                  fieldProps: {
                    onDropdownVisibleChange: open => {
                      const options =
                        methodsMain.getFormSchemas('queryPermissions')[0]?.fieldProps?.options ||
                        [];
                      open && SearchAuthModelRef.value?.show({
                          EID: _?.config_eid,
                          ENAME: methodsMain.getData().name,
                        });
                    },
                  },
                },
              ],
              props,
            );
          }
          return props;
        },
        immediate: true,
      },
      '',
      '',
      {},
    );

    const sqlValue = ref('');
    const cancelPage = () => {
      console.log('取消');
    };
    const savePermissionData = async () => {
      if (loading.value) return;
      console.log('保存');
    };
    const setData = () => {
      methodsMain.setData({
        ename: '这是名称内容',
        queryPermissions: undefined,
      });
    };
    // 查询权限保存
    const searchAuthModelFunSuccess = data => {
      console.log('data', data);
      queryPermissions.value = data;
    };

    //关闭按钮实现
    const closePage = () => {
      let funName =  _.disabled ? '/platform/queryConfiguration/GeneralQueryConfig/SystemBuiltInView' : '/platform/queryConfiguration/GeneralQueryConfig/SystemBuiltInEdit';
      close( 
        funName,
        '/platform/QueryConfiguration/GeneralQueryConfig/GeneralQueryConfigIndex',
      );
    };
    // 查询系统内置数据信息
    const querySystemBuiltInData = (eid: string) => {
      let params = {
        eid: eid,
      };
      useHttp({
        url: '/api/commonquery/commonQuery/front/getCommonQueryConfigList',
        method: 'get',
        params: {
          ...params,
        },
      }).then(result => {
        if (result.code == 200 && result.data) {
          console.log('systemBuiltIn:' + result.data);
          let configData = result.data[0];
          // let refModelCode = JSON.parse(configData?.refModelCode);
          // console.log(refModelCode);
          methodsMain.setData({ name: configData?.ename });
          sqlValue.value = configData?.innerSql;
        }
      });
    };
    onBeforeMount(() => {
      if (typeof _?.config_eid !== 'undefined' && _?.config_eid !== '') {
        querySystemBuiltInData(_?.config_eid);
      }
    });
    // onMounted(() => {
    //   setData();
    // });
    // 监听授权客体字段变化进行复制操作
    /*watch(
      () => queryPermissions.value,
      () => {
        const data = [...queryPermissions.value];
        const options = data.map(item => {
          return {
            value: JSON.stringify({ field: item.field, value: item.value }),
            label: item.custom ? `${item.field}:${item.value}` : item.label,
            disabled: true,
          };
        });
        const selectData = options.map(item => item.value) || [];
        methodsMain.updateSchema([
          {
            dataIndex: 'queryPermissions',
            fieldProps: {
              options: options,
            },
          },
        ]);
        methodsMain.setData({
          queryPermissions: selectData,
        });
        console.log('methodsMain', methodsMain.getData());
      },
    );*/
    return {
      t,
      _,
      schemasBasic,
      formRef,
      props,
      sqlValue,
      cancelPage,
      savePermissionData,
      SearchAuthModelRef,
      loading,
      searchAuthModelFunSuccess,
      closePage,
    };
  },
});
</script>
<style lang="less" scoped>
.top {
  background: #fff;
  padding: 24px 0;
  margin-top: 0;
  border-radius: 8px;
}
.bottom {
  margin-top: 24px;
  background: #fff;
  border-radius: 8px;
}
.exclamation-icon {
  color: @normal-color;
  margin-left: 4px;
  font-size: 16px;
  &:hover {
    color: @info-color;
  }
}
.permission-pllicy-btn {
  text-align: right;
  padding-right: 15px;
  position: fixed;
  background: #fff;
  border: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  box-shadow: 0px -9px 16px 0px rgba(74, 85, 107, 0.07);
  padding: 18px 20px 18px 0;
  button {
    margin-left: 24px;
  }
}
:deep(.permission-pllicy-select-sub .ant-select-selector .ant-select-selection-overflow) {
  flex-wrap: nowrap !important;
  overflow: hidden !important;
}
:deep(.permission-subject-select) {
  .ant-select-arrow {
    display: none;
  }
}
</style>
