<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"
      >
        选中单元格（第{{ cell.row }}行，第{{ cell.col }}列）样式
      </div>
      <div
        class="form-cell"
        v-else-if="cell.row !== undefined && cell.col === undefined"
      >
        第{{ cell.row }}行样式
      </div>
      <div
        class="form-cell"
        v-if="cell.row === undefined && cell.col !== undefined"
      >
        第{{ cell.col }}列样式
      </div>
      <t-space direction="vertical" size="small" class="w-full">
        <div class="form-item">
          <label>背景颜色</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>文字颜色</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>文字大小</label>
          <t-input-number
            class="w-full"
            v-model.number="cell.fontSize"
            theme="column"
            :min="0"
            @change="changeStyles('fontSize')"
            :allowInputOverLimit="false"
            :decimalPlaces="2"
          />
        </div>
      </t-space>
    </div>
  </t-space>
  <t-drawer
    v-model:visible="drawer.visible"
    :header="drawer.header"
    cancelBtn="关闭"
    confirmBtn="运行"
    @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 } 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 res: any;
  if (
    arr[0].indexOf('2d.le5le') !== -1 ||
    arr[0].indexOf('le5le.com/2d') !== -1
  ) {
    res = await getLe5le2d(id, projection);
  } else if (
    arr[0].indexOf('v.le5le') !== -1 ||
    arr[0].indexOf('le5le.com/v') !== -1
  ) {
    res = await getLe5leV(id, projection);
  } else if (
    arr[0].indexOf('3d.le5le') !== -1 ||
    arr[0].indexOf('le5le.com/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('数据不满足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,
});

const getPenData = (data: any) => {
  if (props.pen.name === 'tablePlus') {
    if (!props.pen.styles) {
      props.pen.styles = [];
    }
    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;
      } else {
        cell.value.background = undefined;
        cell.value.textColor = undefined;
        cell.value.fontSize = undefined;
      }
    } else if (props.pen.calculative.activeCol) {
      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;
      } else {
        cell.value.background = undefined;
        cell.value.textColor = undefined;
        cell.value.fontSize = undefined;
      }
    } else if (props.pen.calculative.activeRow) {
      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;
      } else {
        cell.value.background = undefined;
        cell.value.textColor = undefined;
        cell.value.fontSize = undefined;
      }
    } else {
      cell.value.col = undefined;
      cell.value.row = undefined;
      cell.value.background = undefined;
      cell.value.textColor = undefined;
      cell.value.fontSize = 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],
    });
  }
};

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;
}
</style>
