<template>
  <div class="top">
    <p class="card-title">
      <span style="font-size: 18px; font-weight: 550">
        {{ t('queryConfiguration.configCreate.hiddenRulesQuery.hiddenRulesQuery') }}
      </span>
    </p>
    <h-row :gutter="24" class="table-title-margin app-custom-edit-form-header">
      <h-col :span="4">
        <!-- {{ t('permission.dataPermissionPolicy.dataPermissionPolicy.permissionSub.customAttrName') }} -->
        <span>{{ t('queryConfiguration.configCreate.hiddenRulesQuery.operationType') }}</span>
      </h-col>
      <h-col :span="4">
        <span>{{ t('queryConfiguration.configCreate.hiddenRulesQuery.model') }}</span>
      </h-col>
      <h-col :span="6">
        <span>{{ t('queryConfiguration.configCreate.hiddenRulesQuery.field') }}</span>
      </h-col>
      <h-col :span="4">
        <span>{{ t('queryConfiguration.configCreate.hiddenRulesQuery.conditions') }}</span>
      </h-col>
      <h-col :span="4">
        <span>{{ t('queryConfiguration.configCreate.hiddenRulesQuery.value') }}</span>
      </h-col>
      <h-col :span="2" class="app-custom-edit-form-operation" v-if="!hiddenDisable">
        {{ t('platform.common.operate') }}
      </h-col>
    </h-row>
    <h-form
      class="app-custom-edit-form-body"
      ref="formManageRefCustom"
      name="dynamic_form_nest_item"
      :model="attrValidateForm"
      id="Form_hiddenRules"
    >
      <h-row :gutter="24" v-for="(custom, index) in attrValidateForm.custom" :key="custom.key">
        <h-col :span="4">
          <h-form-item
            label=""
            :name="['custom', index, 'operator']"
            :rules="{
              required: true,
              message: t('queryConfiguration.configCreate.hiddenRulesQuery.operationType'),
              trigger: 'blur',
            }"
          >
            <h-select
              v-model:value="custom.operator"
              :optionLabelProp="null"
              :showSearch="false"
              :disabled="hiddenDisable"
              :getPopupContainer="getSelectContainer"
            >
              <h-select-option value="AND">AND</h-select-option>
              <h-select-option value="OR">OR</h-select-option>
            </h-select>
          </h-form-item>
        </h-col>
        <h-col :span="4">
          <h-form-item
            label=""
            :name="['custom', index, 'model']"
            :rules="{
              required: true,
              message: t('queryConfiguration.configCreate.hiddenRulesQuery.model'),
              trigger: 'blur',
            }"
          >
            <h-select
              v-model:value="custom.model"
              :optionLabelProp="null"
              :showSearch="false"
              :disabled="hiddenDisable"
              :options="modelOptions"
              :getPopupContainer="getSelectContainer"
              @change="(value, option) => changeModel(value, option, index)"
            ></h-select>
          </h-form-item>
        </h-col>
        <h-col :span="6">
          <h-form-item
            label=""
            :name="['custom', index, 'field']"
            :rules="{
              required: true,
              message: t('queryConfiguration.configCreate.hiddenRulesQuery.field'),
              trigger: 'blur',
            }"
          >
            <h-select
              v-model:value="custom.field"
              :optionLabelProp="null"
              :showSearch="false"
              :disabled="hiddenDisable"
              :options="fieldOptions"
              :getPopupContainer="getSelectContainer"
              @change="(value, option) => changeField(value, option, index)"
            ></h-select>
          </h-form-item>
        </h-col>
        <h-col :span="4">
          <h-form-item
            label=""
            :name="['custom', index, 'condition']"
            :rules="{
              required: true,
              message: t('queryConfiguration.configCreate.hiddenRulesQuery.conditions'),
              trigger: 'blur',
            }"
          >
            <h-select
              v-model:value="custom.condition"
              :optionLabelProp="null"
              :showSearch="false"
              :disabled="hiddenDisable"
              :getPopupContainer="getSelectContainer"
            >
              <h-select-option value="=">=</h-select-option>
              <h-select-option value="!=">!=</h-select-option>
              <h-select-option value=">">></h-select-option>
              <h-select-option value=">=">>=</h-select-option>
              <h-select-option value="<">&lt;</h-select-option>
              <h-select-option value="<=">&lt;=</h-select-option>
              <h-select-option value="like">like</h-select-option>
            </h-select>
          </h-form-item>
        </h-col>

        <h-col :span="4">
          <h-form-item
            v-if="fieldValueData[custom.field]?.fieldType === 'Enum'"
            label=""
            :name="['custom', index, 'val']"
            :rules="[
              {
                required: true,
                message: t('queryConfiguration.configCreate.hiddenRulesQuery.form.selectMessage'),
                trigger: ['change', 'blur'],
              },
            ]"
          >
            <h-select
              v-model:value="custom.val"
              :optionLabelProp="null"
              :showSearch="false"
              :disabled="hiddenDisable"
              :getPopupContainer="getSelectContainer"
              :options="fieldValueData[custom.field]?.dictList"
            ></h-select>
          </h-form-item>
          <h-form-item
            v-else-if="fieldValueData[custom.field]?.fieldType === 'Date'"
            label=""
            :name="['custom', index, 'val']"
            :rules="[
              {
                required: true,
                message: t('queryConfiguration.configCreate.hiddenRulesQuery.form.dateMessage'),

                trigger: ['change', 'blur'],
              },
            ]"
          >
            <h-date-picker
              v-model:value="custom.val"
              :disabled="hiddenDisable"
              valueFormat="YYYY-MM-DD"
            ></h-date-picker>
          </h-form-item>
          <h-form-item
            v-else-if="
              fieldValueData[custom.field]?.fieldType === 'SingleUserValue' ||
              fieldValueData[custom.field]?.fieldType === 'HBCustomSelect'
            "
            label=""
            :name="['custom', index, 'val']"
            :rules="[
              {
                required: true,
                message: t('queryConfiguration.configCreate.hiddenRulesQuery.form.dateMessage'),

                trigger: ['change', 'blur'],
              },
            ]"
          >
            <h-b-custom-select
              v-model:value="custom.val"
              valueType="string"
              componentType="user"
              dataQueryType="company"
              selectMode="single"
              :selectShowMaxLength="3"
              :showSearch="false"
              :open="false"
              :notFoundContent="null"
              hasPath="1"
            ></h-b-custom-select>
          </h-form-item>
          <h-form-item
            v-else
            label=""
            :name="['custom', index, 'val']"
            :rules="[
              {
                required: true,
                message: t('queryConfiguration.configCreate.hiddenRulesQuery.form.message'),
                pattern: '^\\s*(\\S+\\s*)+$',
                trigger: ['change', 'blur'],
              },
              {
                message: t('queryConfiguration.configCreate.hiddenRulesQuery.form.rules'),
                trigger: 'change',
                max: 20,
              },
            ]"
          >
            <h-input
              v-model:value="custom.val"
              autocomplete="off"
              :placeholder="t('queryConfiguration.configCreate.hiddenRulesQuery.form.message')"
              :disabled="hiddenDisable"
              maxlength="20"
            />
          </h-form-item>
        </h-col>
        <h-col :span="2" class="app-custom-edit-form-operation" v-if="!hiddenDisable">
          <h-form-item>
            <h-button type="link" @click="removeCustom(index)">
              {{ t('platform.common.delete') }}
            </h-button>
          </h-form-item>
        </h-col>
      </h-row>

      <h-form-item v-if="!hiddenDisable">
        <h-button type="dashed" block @click="addCustom">
          <plus-outlined />
          {{ t('platform.common.add') }}
        </h-button>
      </h-form-item>
    </h-form>

    <!-- <div class="permission-pllicy-btn">
      <h-button :loading="loading" @click="cancelPage">{{ t('platform.common.cancel') }}</h-button>
      <h-button :loading="loading" type="primary" @click="savePermissionData">
        {{ t('platform.common.save') }}
      </h-button>
    </div> -->
  </div>
</template>
<script>
import { useI18n } from '@crami/locale';
import { defineComponent, ref, reactive, watch, onBeforeMount } from 'vue';
import { useHttp } from '@crami/http';
import { getUuid } from '@remote/icpx-platform/utils';
/* import { getUuid } from '@/utils/uuid'; */

export default defineComponent({
  name: 'HiddenRulesQuery',
  props: {
    hiddenDisable: {
      type: Boolean,
      default: false,
    },
    modelGroup: {
      type: Object,
    },
    storedData: {
      type: String,
    },
  },
  setup(props) {
    const { t } = useI18n();

    const loading = ref(false);
    const formManageRefCustom = ref();
    const attrValidateForm = reactive({
      custom: [],
    });

    const modelOptions = ref([]);
    const fieldOptions = ref([]);
    let modelField = {};

    const addCustom = () => {
      attrValidateForm.custom.push({
        operator: 'AND',
        model: '',
        field: '',
        condition: '=',
        val: '',

        key: getUuid(5, 5),
      });
    };
    const removeCustom = index => {
      // if (attrValidateForm.custom.length == 1) {
      //   return;
      // }
      console.log('index', index);
      attrValidateForm.custom.splice(index, 1);
    };

    const savePermissionData = async () => {
      if (loading.value) return;
      console.log('保存');
    };
    // 以[key]:[value]的形式存放字段值
    let fieldValueData = ref({});
    // 获取字段列表
    function fetchAllFields(modelGroup) {
      let params = {
        tableCode: modelGroup?.masterModel?.value,
        children: modelGroup?.children,
      };
      async function fetchData() {
        const result = await useHttp({
          url: '/api/commonquery/commonQuery/manage/getFieldsByModels',
          method: 'post',
          params: {
            ...params,
          },
        });

        if (result.code == 200 && result.data) {
          let tempModelList = [];
          let tempFieldList = [];
          fieldValueData.value = {};
          for (let [index, fieldItem] of result.data.entries()) {
            console.log(index, fieldItem);
            let tableInfo = { value: fieldItem.belongTable, label: fieldItem.tableDesc };
            let fieldInfo = {
              value: fieldItem.fieldName,
              label: fieldItem.fieldDesc + '(' + fieldItem.fieldName + ')',
              fieldType: fieldItem.fieldType,
              dictList: fieldItem.dictList,
            };
            fieldValueData.value[fieldItem.fieldName] = fieldItem;
            tempFieldList.push(fieldInfo);
            let existTable = false;
            for (let storedItem of tempModelList) {
              if (storedItem.value == tableInfo.value) {
                existTable = true;
                break;
              }
            }
            if (existTable) {
              modelField[tableInfo.value] = modelField[tableInfo.value].concat(fieldInfo);
            } else {
              tempModelList.push(tableInfo);
              modelField[tableInfo.value] = [].concat(fieldInfo);
            }
          }
          modelOptions.value = tempModelList;
          //fieldOptions.value = tempFieldList;
          console.log(modelGroup.masterModel);
          changeModel(
            '',
            { value: modelGroup.masterModel.value, label: modelGroup.masterModel.label },
            0,
          );

          console.log('hiddenRulesQuery fetchAllFields length:' + tempFieldList.length);
        }
      }
      if (modelGroup?.masterModel != null) {
        fetchData();
      }
    }
    const getSelectContainer = () => {
      return document.getElementById('Form_hiddenRules');
    };
    const changeModel = (val, option, index) => {
      console.log(option.value);
      if (attrValidateForm.custom[index]) {
        attrValidateForm.custom[index].modelKey = option.label;
      }
      if (option.value in modelField) {
        fieldOptions.value = [].concat(modelField[option.value]);
      }
    };
    const changeField = (val, option, index) => {
      attrValidateForm.custom[index].FieldKey = option.label;
      attrValidateForm.custom[index].val = '';
    };

    watch(
      () => ({ ...props.modelGroup }),
      (newVal, oldVal) => {
        console.log('hiddenRulesQuery newVal:' + newVal);
        console.log('hiddenRulesQuery oldVal:' + oldVal);
        console.log('hiddenRulesQuery modelGroup:' + props.modelGroup);
        attrValidateForm.custom.length = 0;
        fetchAllFields(props.modelGroup);
      },
    );

    watch(
      () => props.storedData,
      (newVal, oldVal) => {
        console.log('hiddenRulesQuery storedData newVal:' + JSON.stringify(newVal));
        console.log('hiddenRulesQuery storedData oldVal:' + JSON.stringify(oldVal));
        if (typeof newVal !== 'undefined' && newVal.length > 0) {
          let storedDataJson = JSON.parse(newVal);
          storedDataJson.forEach(element => {
            attrValidateForm.custom.push({
              key: element.id,
              operator: element.splicer,
              model: element.tableName,
              field: element.fieldName,
              modelKey: element.tableDesc,
              FieldKey: element.fieldDesc,
              condition: element.operator,
              val: element.actualValueDesc,
            });
          });
        }
      },
    );
    onBeforeMount(() => {
      fetchAllFields(props.modelGroup);
    });
    return {
      t,
      savePermissionData,
      formManageRefCustom,
      attrValidateForm,
      addCustom,
      removeCustom,
      fetchAllFields,
      modelOptions,
      fieldOptions,
      modelField,
      changeModel,
      changeField,
      fieldValueData,
      getSelectContainer,
    };
  },
});
</script>
<style lang="less" scoped>
@import '@/theme/default/variables.less';

.top {
  background: #fff;
  padding: 20px 24px;
  margin-top: 0;
  border-radius: 8px;
}
.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;
  }
}
.exclamation-icon {
  color: @normal-color;
  margin-left: 4px;
  &:hover {
    color: @info-color;
  }
}
.table-title-margin {
  margin-bottom: 10px;
  text-align: center;
  div:last-child {
    padding-right: 2px !important;
  }
}
</style>
