<template>
  <t-space direction="vertical" size="small" class="w-full">
    <div v-for="item in props.pen.props.custom" class="form-item">
      <label :title="item.label">{{ item.label }}</label>
      <t-checkbox
        class="ml-8"
        v-if="item.type === 'bool'"
        v-model="props.pen[item.key]"
        @change="changeValue(item.key)"
      />
      <t-input-number
        class="w-full"
        v-else-if="item.type === 'number'"
        v-model.number="props.pen[item.key]"
        theme="column"
        :max="item.max"
        :min="item.min"
        @change="changeValue(item.key)"
        :placeholder="item.placeholder"
        :allowInputOverLimit="false"
        :decimalPlaces="2"
      />
      <t-color-picker
        class="w-full"
        v-else-if="item.type === 'color'"
        :enable-alpha="true"
        :recent-colors="null"
        format="CSS"
        :swatch-colors="defaultPureColor"
        :color-modes="['monochrome']"
        :show-primary-color-preview="false"
        v-model="props.pen[item.key]"
        @change="changeValue(item.key)"
        :placeholder="item.placeholder"
      />
      <t-select
        class="w-full"
        v-else-if="item.type === 'select'"
        size="small"
        :options="item.options"
        v-model="props.pen[item.key]"
        @change="changeValue(item.key)"
        :placeholder="item.placeholder"
      />
      <!-- <t-button
              class="ml-8"
              v-else-if="item.type === 'code'"
              shape="square"
              variant="outline"
              style="width: 24px"
              @click="showPropsEdit(item)"
            >
              <ellipsis-icon slot="icon"/>
            </t-button> -->
      <t-button
        class="ml-8"
        v-else-if="item.type === 'code'"
        shape="square"
        variant="outline"
        style="width: 24px"
        @click="showDrawer(item)"
      >
        <ChevronLeftDoubleIcon slot="icon" />
      </t-button>
      <t-slider
        v-else-if="item.type === 'slider'"
        v-model="props.pen[item.key]"
        :min="0"
        :max="1"
        :step="0.01"
        @change="changeValue(item.key)"
      />
      <t-switch
        size="small"
        class="mt-8 ml-8"
        v-else-if="item.type === 'switch'"
        v-model="props.pen[item.key]"
        @change="changeValue(item.key)"
      />
      <t-input
        class="w-full"
        v-else
        v-model="props.pen[item.key]"
        @change="changeValue(item.key)"
        :placeholder="item.placeholder"
      />
    </div>
    <div v-if="props.pen.name === 'tablePlus'">
      <div
        class="form-cell"
        v-if="cell.row !== undefined && cell.col !== undefined"
      >
        {{$t( '选中单元格' )}}（{{$t( '第' )}}{{ cell.row }}{{$t( '行' )}}，{{$t( '第' )}}{{ cell.col }}{{$t( '列' )}}）{{$t( '样式' )}}
      </div>
      <div
        class="form-cell"
        v-else-if="cell.row !== undefined && cell.col === undefined"
      >
        {{$t( '第' )}}{{ cell.row }}{{$t( '行样式' )}}
      </div>
      <div
        class="form-cell"
        v-if="cell.row === undefined && cell.col !== undefined"
      >
        {{$t( '第' )}}{{ cell.col }}{{$t( '列样式' )}}
      </div>
      <t-space direction="vertical" size="small" class="w-full">
        <div class="form-item">
          <label>{{$t( '背景颜色' )}}</label>
          <t-color-picker
            class="w-full"
            :enable-alpha="true"
            :recent-colors="null"
            format="CSS"
            :swatch-colors="defaultPureColor"
            :color-modes="['monochrome']"
            :show-primary-color-preview="false"
            v-model="cell.background"
            @change="changeStyles('background')"
          />
        </div>
        <div class="form-item">
          <label>{{$t( '文字颜色' )}}</label>
          <t-color-picker
            class="w-full"
            :enable-alpha="true"
            :recent-colors="null"
            format="CSS"
            :swatch-colors="defaultPureColor"
            :color-modes="['monochrome']"
            :show-primary-color-preview="false"
            v-model="cell.textColor"
            @change="changeStyles('textColor')"
          />
        </div>
        <div class="form-item">
          <label>{{$t( '文字大小' )}}</label>
          <t-input-number
            class="w-full"
            v-model.number="cell.fontSize"
            theme="column"
            :min="0"
            @change="changeStyles('fontSize')"
            :allowInputOverLimit="false"
            :decimalPlaces="2"
            width="50%"
          />
          <t-button
            :class="{ active: cell.fontWeight === 'bold' }"
            class="ml-8 icon"
            shape="rectangle"
            variant="text"
            @click="
              cell.fontWeight === 'bold'
                ? (cell.fontWeight = 'normal')
                : (cell.fontWeight = 'bold');
                changeStyles('fontWeight');
            "
          >
            B
          </t-button>

          <t-button
            :class="{ active: cell.fontStyle === 'italic' }"
            class="ml-4 icon"
            shape="rectangle"
            variant="text"
            @click="
              cell.fontStyle === 'italic'
                ? (cell.fontStyle = 'normal')
                : (cell.fontStyle = 'italic');
                changeStyles('fontStyle');
            "
            style="font-style: italic; font-family: serif"
            >I</t-button
          >
        </div>
        <div class="form-item">
          <label>{{$t( '文本对齐' )}}</label>
          <t-radio-group
            size="small"
            v-model="cell.textAlign"
            default-value="center"
            @change="changeStyles('textAlign')"
          >
            <t-radio-button value="left">
              <t-tooltip :content="$t('居左')" placement="top">
                <format-vertical-align-left-icon />
              </t-tooltip>
            </t-radio-button>
            <t-radio-button value="center">
              <t-tooltip :content="$t('水平居中')" placement="top">
                <format-vertical-align-center-icon />
              </t-tooltip>
            </t-radio-button>
            <t-radio-button value="right">
              <t-tooltip :content="$t('居右')" placement="top">
                <format-vertical-align-right-icon />
              </t-tooltip>
            </t-radio-button>
          </t-radio-group>
          <t-tooltip :content="$t('水平偏移')">
            <t-input
              placeholder="X"
              v-model.number="cell.textLeft"
              style="width: 60px; margin-left: 8px"
              @change="changeStyles('textLeft')"
            />
          </t-tooltip>
        </div>
      </t-space>
    </div>
    <div v-if="props.pen.name === 'combine'" class="form-item">
      <label > {{$t( '是否绘制' )}} </label>
      <t-checkbox
        class="ml-8"
        v-model="props.pen['draw']"
        @change="changeValue('draw')"
      />
    </div>
  </t-space>
  <t-drawer
    v-model:visible="drawer.visible"
    :header="drawer.header"
    :cancelBtn="$t('关闭')"
    :confirmBtn="$t('运行')"
    @confirm="onConfirmDrawer"
    :closeOnOverlayClick="false"
    :sizeDraggable="true"
  >
    <div style="height: 100%">
      <CodeEditor
        style="height: 100%"
        :key="drawer.randomkey"
        :json="true"
        :language="'json'"
        v-model="drawer.value"
      />
    </div>
    <div class="gray" style="font-size: 12px">
      {{ drawer.placeholder }}
    </div>
  </t-drawer>
</template>

<script lang="ts" setup>
import { reactive, defineComponent, ref, onMounted, onUnmounted } from 'vue';
import {
  getter,
  setter,
  queryURLParams,
  deepClone,
  getAllChildren,
  Pen,
} from '@meta2d/core';
import { getLe5le3d, getLe5leV, getLe5le2d } from '@/services/api';
import { updatePen } from './pen';
import { defaultGradientColor, defaultPureColor } from '@/services/defaults';
import { MessagePlugin } from 'tdesign-vue-next';
import { s8 } from '@/services/random';
import CodeEditor from '@/views/components/common/CodeEditor.vue';
import { ChevronLeftDoubleIcon, FormatVerticalAlignLeftIcon, FormatVerticalAlignCenterIcon, FormatVerticalAlignRightIcon } from 'tdesign-icons-vue-next';

const props = defineProps<{
  pen: any;
}>();

const changeValue = (prop: string) => {
  updatePen(props.pen, prop);
  // selections.pen[prop] = getter(props.pen, prop);
  if (prop === 'iframe') {
    getThumbImg();
  }
  if (prop === 'apiEnable') {
    meta2d.penNetwork(props.pen);
    meta2d.connectNetwork();
  }
};

const getThumbImg = async () => {
  //改iframe地址后
  let arr = props.pen.iframe.split('?');
  let id = queryURLParams(arr[1]).id;
  if (!id) {
    return;
  }
  // let projection = {
  //   image: 1,
  //   _id: 1,
  //   name: 1,
  // };
  let projection = 'image,id,name';
  let key = 'le5le.com'
  if(location.origin.indexOf('le5le.com')===-1){
      key = ''
  }
  let res: any;
  if (
    arr[0].indexOf(`2d.${key}`) !== -1 ||
    arr[0].indexOf(`${key}/2d`) !== -1
  ) {
    res = await getLe5le2d(id, projection);
  } else if (
    arr[0].indexOf(`v.${key}`) !== -1 ||
    arr[0].indexOf(`${key}/v`) !== -1|| arr[0].indexOf('/preview') !== -1
  ) {
    res = await getLe5leV(id, projection);
  } else if (
    arr[0].indexOf(`3d.${key}`) !== -1 ||
    arr[0].indexOf(`${key}/3d`) !== -1
  ) {
    res = await getLe5le3d(id, projection);
  }
  if (res) {
    props.pen.thumbImg = res.image;
    props.pen.calculative && (props.pen.calculative.img = null);
  }
  props.pen.onRenderPenRaw?.(props.pen);
};

const drawer = reactive<any>({
  visible: false,
});

const showDrawer = (item: any) => {
  drawer.key = item.key;
  drawer.header = `${item.label}(${item.key})`;
  drawer.value = deepClone(props.pen[item.key]);
  drawer.placeholder = item.placeholder;
  drawer.randomkey = s8(); //props.pen.id;
  drawer.visible = true;
};

const onConfirmDrawer = () => {
  if (!drawer.value) {
    MessagePlugin.error($t('数据不满足json格式'));
    return;
  }
  props.pen[drawer.key] = drawer.value;
  updatePen(props.pen, drawer.key);
};

const cell = ref({
  col: undefined,
  row: undefined,
  background: undefined,
  textColor: undefined,
  fontSize: undefined,
  fontWeight: undefined,
  fontStyle: undefined,
  textAlign: undefined,
  textLeft: undefined,
});

const getPenData = (data: any) => {
  if (props.pen.name === 'tablePlus') {
    if (!props.pen.styles) {
      props.pen.styles = [];
    }
    if (props.pen.calculative.activeCol !== undefined) {
      cell.value.col = props.pen.calculative.activeCol;
      cell.value.row = undefined;
      let found = props.pen.styles.findIndex((item: any) => {
        return item.row === undefined && item.col === cell.value.col;
      });
      if (found !== -1) {
        cell.value.background = props.pen.styles[found].background;
        cell.value.textColor = props.pen.styles[found].textColor;
        cell.value.fontSize = props.pen.styles[found].fontSize;
        cell.value.fontWeight = props.pen.styles[found].fontWeight;
        cell.value.fontStyle = props.pen.styles[found].fontStyle;
        cell.value.textAlign = props.pen.styles[found].textAlign;
        cell.value.textLeft = props.pen.styles[found].textLeft;
      } else {
        cell.value.background = undefined;
        cell.value.textColor = undefined;
        cell.value.fontSize = undefined;
        cell.value.fontWeight = undefined;
        cell.value.fontStyle = undefined;
        cell.value.textAlign = undefined;
        cell.value.textLeft = undefined;
      }
    } else if (props.pen.calculative.activeRow !== undefined) {
      cell.value.col = undefined;
      cell.value.row = props.pen.calculative.activeRow;

      let found = props.pen.styles.findIndex((item: any) => {
        return item.row === cell.value.row && item.col === undefined;
      });
      if (found !== -1) {
        cell.value.background = props.pen.styles[found].background;
        cell.value.textColor = props.pen.styles[found].textColor;
        cell.value.fontSize = props.pen.styles[found].fontSize;
        cell.value.fontWeight = props.pen.styles[found].fontWeight;
        cell.value.fontStyle = props.pen.styles[found].fontStyle;
        cell.value.textAlign = props.pen.styles[found].textAlign;
        cell.value.textLeft = props.pen.styles[found].textLeft;
      } else {
        cell.value.background = undefined;
        cell.value.textColor = undefined;
        cell.value.fontSize = undefined;
        cell.value.fontWeight = undefined;
        cell.value.fontStyle = undefined;
        cell.value.textAlign = undefined;
        cell.value.textLeft = undefined;
      }
    } else if (props.pen.calculative.activeCell) {
      cell.value.col = props.pen.calculative.activeCell.col;
      cell.value.row = props.pen.calculative.activeCell.row;
      let found = props.pen.styles.findIndex((item: any) => {
        return item.row === cell.value.row && item.col === cell.value.col;
      });
      if (found !== -1) {
        cell.value.background = props.pen.styles[found].background;
        cell.value.textColor = props.pen.styles[found].textColor;
        cell.value.fontSize = props.pen.styles[found].fontSize;
        cell.value.fontWeight = props.pen.styles[found].fontWeight;
        cell.value.fontStyle = props.pen.styles[found].fontStyle;
        cell.value.textAlign = props.pen.styles[found].textAlign;
        cell.value.textLeft = props.pen.styles[found].textLeft;
      } else {
        cell.value.background = undefined;
        cell.value.textColor = undefined;
        cell.value.fontSize = undefined;
        cell.value.fontWeight = undefined;
        cell.value.fontStyle = undefined;
        cell.value.textAlign = undefined;
        cell.value.textLeft = undefined;
      }
    } else {
      cell.value.col = undefined;
      cell.value.row = undefined;
      cell.value.background = undefined;
      cell.value.textColor = undefined;
      cell.value.fontSize = undefined;
      cell.value.fontWeight = undefined;
      cell.value.fontStyle = undefined;
      cell.value.textAlign = undefined;
      cell.value.textLeft = undefined;
    }
  }
};

const changeStyles = (key) => {
  //更新属性
  if (!props.pen.styles) {
    props.pen.styles = [];
  }
  let found = props.pen.styles.findIndex((item: any) => {
    return item.row === cell.value.row && item.col === cell.value.col;
  });
  if (found !== -1) {
    props.pen.styles[found][key] = cell.value[key];
  } else {
    props.pen.styles.push({
      row: cell.value.row,
      col: cell.value.col,
      [key]: cell.value[key],
    });
  }
  meta2d.render();
};

onMounted(() => {
  meta2d.on('click', getPenData);
  getPenData({});
});

onUnmounted(() => {
  meta2d.off('click', getPenData);
});
</script>
<style lang="postcss" scoped>
.form-cell {
  font-size: 13px;
  /* font-weight: 700; */
  color: var(--color);
  padding-top: 16px;
  padding-bottom: 8px;
}
.form-item .t-input-number {
  width: 45%;
}
</style>
