<!--
 * @Description: 组件属性控件
-->
<template>
  <div class="properties-content">
    <div class="properties-body" v-if="formConfig.currentItem">
      <Empty class="hint-box" v-if="!formConfig.currentItem.key" description="未选择组件" />
      <Form
        label-align="left"
        layout="vertical"
        v-if="
          ['Grid'].includes(formConfig.currentItem.component) &&
          formConfig.currentItem.type == 'subTable'
        "
      >
        <FormItem v-for="item in subTableOptions" :key="item.name" :label="item.label">
          <!--     处理数组属性，placeholder       -->
          <div v-if="item.children">
            <template v-for="(child, index) of item.children" :key="index">
              <component
                v-if="child.component"
                v-bind="child.componentProps"
                v-model:value="formConfig.currentItem.componentProps[item.name][index]"
                :is="child.component"
              />
            </template>
          </div>
          <!--     如果不是数组，则正常处理属性值       -->
          <component
            v-else-if="item.component"
            class="component-prop"
            v-bind="item.componentProps"
            :is="item.component"
            @change="handleFieldTableChange"
            v-model:value="formConfig.currentItem.componentProps[item.name]"
          />
        </FormItem>

        <FormItem label="控制属性">
          <Col v-for="item in SubControllOptions" :key="item.name">
            <Checkbox
              v-if="showControlAttrs(item.includes)"
              v-bind="item.componentProps"
              v-model:checked="formConfig.currentItem.componentProps[item.name]"
            >
              {{ item.label }}
            </Checkbox>
          </Col>
        </FormItem>
      </Form>
      <Form label-align="left" layout="vertical" v-else>
        <!--    循环遍历渲染组件属性      -->

        <div v-if="formConfig.currentItem && formConfig.currentItem.componentProps">
          <FormItem v-for="item in inputOptions" :key="item.name" :label="item.label">
            <!--     处理数组属性，placeholder       -->
            <div v-if="item.children">
              <template v-for="(child, index) of item.children" :key="index">
                <component
                  v-if="child.component"
                  v-bind="child.componentProps"
                  v-model:value="formConfig.currentItem.componentProps[item.name][index]"
                  :is="child.component"
                />
              </template>
            </div>
            <!--     如果不是数组，则正常处理属性值       -->
            <component
              v-else-if="item.component"
              class="component-prop"
              v-bind="item.componentProps"
              :is="item.component"
              @change="handleFieldTableChange"
              v-model:value="formConfig.currentItem.componentProps[item.name]"
            />
          </FormItem>
          <FormItem label="控制属性">
            <Col v-for="item in controlOptions" :key="item.name">
              <Checkbox
                v-if="showControlAttrs(item.includes)"
                v-bind="item.componentProps"
                v-model:checked="formConfig.currentItem.componentProps[item.name]"
              >
                {{ item.label }}
              </Checkbox>
            </Col>
          </FormItem>
          <FormItem label="标题集合" v-if="['Transfer'].includes(formConfig.currentItem.component)">
            <Input v-model:value="formConfig.currentItem.componentProps.titles[0]" />
            <Input v-model:value="formConfig.currentItem.componentProps.titles[1]" />
          </FormItem>
        </div>
        <FormItem label="关联字段">
          <Select
            mode="multiple"
            v-model:value="formConfig.currentItem['link']"
            :options="linkOptions"
          />
        </FormItem>
        <FormItem label="图标" v-if="['Button'].includes(formConfig.currentItem.component)">
          <IconPicker v-model:value="formConfig.currentItem.componentProps.icon" />
        </FormItem>
        <FormItem label="脚本" v-if="['Button'].includes(formConfig.currentItem.component)">
          <a-button size="mini" @click="handleButtonClick"> 点击脚本 </a-button>
        </FormItem>

        <FormItem
          label="选项"
          v-if="
            [
              'CheckboxGroup',
              'RadioGroup',
              'TreeSelect',
              'Cascader',
              'Transfer',
              'AutoComplete',
              'Tabs',
              'CardGroup',
            ].includes(formConfig.currentItem.component)
          "
        >
          <FormOptions />
        </FormItem>
        <FormItem label="选项" v-if="['Select'].includes(formConfig.currentItem.component)">
          <div class="select-radio">
            <a-radio-group v-model:value="formConfig.currentItem.dataType" button-style="solid">
              <a-radio-button value="1">静态数据</a-radio-button>
              <a-radio-button value="2">数据字典</a-radio-button>
            </a-radio-group>
          </div>
          <template v-if="formConfig.currentItem.dataType === '1'">
            <FormOptions />
          </template>
          <template v-else-if="formConfig.currentItem.dataType === '2'">
            <a-select
              v-model:value="formConfig.currentItem.dataCode"
              show-search
              style="width: 100%"
              placeholder="请选择字典类型"
              :default-active-first-option="false"
              :show-arrow="false"
              :filter-option="false"
              :not-found-content="null"
              :options="selectDictionaryData"
              @search="handleSearch"
              @change="handleChange"
              @focus="handleSelectFocus"
            ></a-select>
          </template>
        </FormItem>
        <FormItem
          label="栅格"
          v-if="
            ['Grid'].includes(formConfig.currentItem.component) &&
            formConfig.currentItem.label == '栅格布局'
          "
        >
          <FormOptions />
        </FormItem>
      </Form>
    </div>
  </div>
  <BasicModal
    @register="buttonScriptModal"
    title="按钮点击脚本"
    :height="500"
    :width="1000"
    :useWrapper="false"
    @ok="handleSubmit"
  >
    <div class="alertModal">
      <div class="alertModal_content">
        <a-textarea
          v-model:value="formContent"
          autosize
          :auto-size="{ minRows: 22, maxRows: 22 }"
        />
      </div>
      <div class="alertModal_content">
        <a-textarea
          class="alertModal_content-textarea"
          v-model:value="formItemPropsScript"
          autosize
          readOnly
          :auto-size="{ minRows: 22, maxRows: 22 }"
        />
      </div>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import {
    Empty,
    Input,
    Form,
    FormItem,
    Switch,
    Checkbox,
    Select,
    InputNumber,
    RadioGroup,
    Col,
    Row,
    message,
  } from 'ant-design-vue';
  import { IconPicker } from '@/components/Icon';
  import RadioButtonGroup from '@/components/Form/src/components/RadioButtonGroup.vue';
  import { computed, defineComponent, ref, watch, inject } from 'vue';
  import { useFormDesignState } from '../../../hooks/useFormDesignState';
  import {
    baseComponentControlAttrs,
    baseComponentAttrs,
    baseComponentCommonAttrs,
    componentPropsFuncs,
    designSubTableAttrs,
    designSubControlAttrs,
  } from '../../VFormDesign/config/componentPropsConfig';
  import FormOptions from './FormOptions.vue';
  import { formItemsForEach, remove } from '../../../utils';
  import { IBaseFormAttrs } from '../config/formItemPropsConfig';
  import { getOutKeyList } from '@/api/formdesign/index';
  import { BasicModal, useModal } from '@/components/Modal';
  import { formItemPropsScript } from '../../VFormDesign/config/formItemPropsScript';
  import { getDictionaryType, getDictionary } from '@/api/sys/categories.ts';
  import { useOnlineFormDesignStore } from '@/store/modules/onlineFormDesign';

  export default defineComponent({
    name: 'ComponentProps',
    components: {
      FormOptions,
      Empty,
      Input,
      Form,
      FormItem,
      Switch,
      Checkbox,
      Select,
      InputNumber,
      RadioGroup,
      RadioButtonGroup,
      Col,
      Row,
      message,
      BasicModal,
      useModal,
      IconPicker,
    },
    setup() {
      const onlineFormDesignStore = useOnlineFormDesignStore();
      let fieldTableValue = ref();
      let FieldTableOptions = ref();
      let ChlidTableOptions = ref(); //子表
      let receivedData = ref();
      const selectRadio = ref(0);
      const selectDictionary = ref();
      const selectDictionaryData = computed(() => onlineFormDesignStore.getSelectDictionaryData());
      const timeout = ref();
      const handleNextStepsData = inject('handleNextStepsData');
      let currentIndex = ref(); //判断是不是子表里的
      watch(
        () => handleNextStepsData, // 点击下一步按钮传递的参数
        (newVal) => {
          FieldTableOptions.value = [];
          ChlidTableOptions.value = [];
          if (newVal && newVal.value && newVal.value.scheme && newVal.value.scheme.scheme) {
            receivedData.value = JSON.parse(newVal.value.scheme.scheme);
            receivedData.value.db.forEach((item) => {
              FieldTableOptions.value.push({
                value: item.name,
                label: item.name,
              });
              if (item.type == 'chlid') {
                ChlidTableOptions.value.push({
                  value: item.name,
                  label: item.name,
                });
              }
            });
          }
        },
        { deep: true, immediate: true },
      );
      const handleSearch = (val: string) => {
        onlineFormDesignStore.getSelectData(val);
      };
      const handleSelectFocus = () => {
        onlineFormDesignStore.getSelectData('');
      };
      const handleChange = (code: string) => {
        onlineFormDesignStore.setSelectOptions(formConfig.value.currentItem.field, code);
      };
      let FieldNamesOptions = ref<SelectProps['options']>([]);

      const fetch = () => {
        if (!fieldTableValue.value || typeof fieldTableValue.value !== 'string') {
          return;
        }

        getOutKeyList({
          tableNames: fieldTableValue.value,
          dbCode: receivedData.value.dbCode,
        }).then((data: Recordable) => {
          let arr: any[] = [];
          if (data && data[0]) {
            data[0].db_codecolumnsList.forEach((item) => {
              arr.push({
                label: item.dbColumnName + '(' + item.description + ')',
                value: item.dbColumnName,
                csType: item.csType,
              });
            });
            FieldNamesOptions.value = arr;
          }
        });
      };
      const handleFieldTableChange = (e) => {
        fieldTableValue.value = e;
        fetch();
        inputOptions.value.forEach((item) => {
          if (item.name == 'fieldName') {
            item.componentProps.options = FieldNamesOptions;
          }
        });
      };

      // 让compuated属性自动更新

      const allOptions = ref([] as Omit<IBaseFormAttrs, 'tag'>[]);

      const showControlAttrs = (includes: string[] | undefined) => {
        if (!includes) return true;
        return includes.includes(formConfig.value.currentItem!.component);
      };

      const { formConfig } = useFormDesignState();
      if (formConfig.value.currentItem) {
        formConfig.value.currentItem.componentProps =
          formConfig.value.currentItem.componentProps || {};
      }
      watch(
        () => formConfig.value.currentItem?.field,
        (_newValue, oldValue) => {
          // currentIndex.value = formConfig.value.schemas.findIndex(
          //   (element) => element.field === formConfig.value.currentItem.field,
          // );
          formConfig.value.schemas &&
            formItemsForEach(formConfig.value.schemas, (item) => {
              if (item.link) {
                const index = item.link.findIndex((linkItem) => linkItem === oldValue);
                index !== -1 && remove(item.link, index);
              }
            });
        },
      );

      const thisFormType: any = inject('thisFormType');
      const formType_design = ref();
      watch(
        () => thisFormType,
        () => {
          formType_design.value = thisFormType.value?.info?.formType | 0;
        },
        { deep: true, immediate: true },
      );

      watch(
        () => formConfig.value.currentItem && formConfig.value.currentItem.component,
        () => {
          // console.log(formConfig.value);
          // currentIndex.value = formConfig.value.schemas.findIndex(
          //   (element) => element.field === formConfig.value.currentItem.field,
          // );
          allOptions.value = [];
          baseComponentControlAttrs.forEach((item) => {
            item.category = 'control';
            if (!item.includes) {
              // 如果属性没有include，所有的控件都适用

              allOptions.value.push(item);
            } else if (item.includes.includes(formConfig.value.currentItem!.component)) {
              // 如果有include，检查是否包含了当前控件类型
              allOptions.value.push(item);
            }
          });

          baseComponentCommonAttrs.forEach((item) => {
            if (
              (formType_design.value != 2 &&
                !['Divider', 'Button'].includes(formConfig.value.currentItem?.component)) ||
              !['dataTable', 'fieldName'].includes(item.name)
            ) {
              item.category = 'input';
              if (item.includes) {
                if (item.includes.includes(formConfig.value.currentItem!.component)) {
                  allOptions.value.push(item);
                }
              } else if (item.exclude) {
                if (!item.exclude.includes(formConfig.value.currentItem!.component)) {
                  allOptions.value.push(item);
                }
              } else {
                allOptions.value.push(item);
              }
            }
          });

          baseComponentAttrs[formConfig.value.currentItem!.component] &&
            baseComponentAttrs[formConfig.value.currentItem!.component].forEach(async (item) => {
              if (item.component) {
                if (['Switch', 'Checkbox', 'Radio'].includes(item.component as string)) {
                  item.category = 'control';
                  allOptions.value.push(item);
                } else {
                  item.category = 'input';
                  allOptions.value.push(item);
                }
              }
            });
        },
        {
          immediate: true,
        },
      );
      // 控制性的选项
      const controlOptions = computed(() => {
        return allOptions.value.filter((item) => {
          return item.category == 'control';
        });
      });

      // 控制性的选项
      const SubControllOptions = computed(() => {
        return designSubControlAttrs;
      });

      // 非控制性选择
      const inputOptions = computed(() => {
        fetch();
        let arr = allOptions.value.filter((item) => {
          return item.category == 'input';
        });
        console.log(arr);
        console.log(currentIndex.value);
        arr.forEach((item) => {
          if (item.name == 'dataTable') {
            if (currentIndex.value == -1) {
              item.componentProps.options = ChlidTableOptions;
            } else {
              item.componentProps.options = FieldTableOptions;
            }
          }
          if (item.name == 'fieldName') {
            item.componentProps.options = FieldNamesOptions;
          }
        });
        return arr;
      });

      const subTableOptions = computed(() => {
        let arr = designSubTableAttrs;
        arr.forEach((item) => {
          if (item.name == 'dataTable') {
            item.componentProps.options = ChlidTableOptions;
          }
          if (item.name == 'fieldName') {
            item.componentProps.options = FieldNamesOptions;
          }
        });
        return arr;
      });
      watch(
        () => formConfig.value.currentItem!.componentProps,
        () => {
          const func = componentPropsFuncs[formConfig.value.currentItem!.component];
          if (func) {
            func(formConfig.value.currentItem!.componentProps, allOptions.value);
          }
          fieldTableValue.value = formConfig.value?.currentItem?.componentProps?.dataTable;
          handleFieldTableChange(formConfig.value?.currentItem?.componentProps?.dataTable);
        },
        {
          immediate: true,
          deep: true,
        },
      );
      const linkOptions = computed(() => {
        return (
          formConfig.value.schemas &&
          formConfig.value.schemas
            .filter((item) => item.key !== formConfig.value.currentItem!.key)
            .map(({ label, field }) => ({ label: label + '/' + field, value: field }))
        );
      });
      // 脚本
      const formContent: any = ref('');
      // 脚本窗口
      const [buttonScriptModal, { openModal, closeModal }] = useModal();
      // 点击脚本按钮
      function handleButtonClick() {
        formContent.value = formConfig.value.currentItem.componentProps?.clickCode;
        openModal();
      }
      // 脚本窗口提交
      function handleSubmit() {
        if (!checkChinese(formContent.value)) {
          message.warning('脚本的代码部分不能含有中文字符！');
          return;
        }
        formConfig.value.currentItem.componentProps.clickCode = formContent.value;
        closeModal();
      }
      // 检查脚本的运行代码是否含有中文
      function checkChinese(str) {
        // 分割字符串为多行
        const lines = str.split('\n');
        let flag = true;

        // 遍历每一行
        for (const line of lines) {
          // 先检查并移除console.log及其后的内容
          const consoleIndex = line.indexOf('console.log');
          let partToCheck = line;
          if (consoleIndex !== -1) {
            partToCheck = line.substring(0, consoleIndex).trim(); // 移除console.log及其后的内容，并去掉前导空格
          }

          // 再检查'//'
          const commentIndex = partToCheck.indexOf('//');
          // 如果有'//'，检查'//'前的部分并去掉前导空格；如果没有，保留原部分
          partToCheck =
            commentIndex !== -1 ? partToCheck.substring(0, commentIndex).trim() : partToCheck;
          // 代码部分不能含有中文字符
          console.log(partToCheck);

          if (/[\u4e00-\u9fa5]/.test(partToCheck)) {
            flag = false;
          }
        }
        return flag;
      }
      return {
        formConfig,
        showControlAttrs,
        linkOptions,
        controlOptions,
        SubControllOptions,
        inputOptions,
        subTableOptions,
        fieldTableValue,
        FieldTableOptions,
        ChlidTableOptions,
        handleFieldTableChange,
        fetch,
        BasicModal,
        formContent,
        formItemPropsScript,
        buttonScriptModal,
        openModal,
        closeModal,
        handleButtonClick,
        handleSubmit,
        selectRadio,
        selectDictionary,
        selectDictionaryData,
        handleSearch,
        handleChange,
        handleSelectFocus,
      };
    },
  });
</script>

<style lang="less" scoped>
  .select-radio {
    display: flex;
    justify-content: center;
    margin-bottom: 15px;
  }
  .alertModal {
    display: flex;
    background-color: @border-color-base;

    &_content {
      width: 50%;
      padding: 1px;

      &-textarea {
        background-color: @component-onlineform-formdesign-alert-background-color;
      }
    }
  }
</style>
