<template>
  <div class="props">
    <t-tabs v-model="data.tab">
      <t-tab-panel :value="1" :label="$t('画布')">
        <t-space direction="vertical" size="small" class="panel">
          <div class="form-item">
            <label>{{$t('文件名')}}</label>
            <t-input class="w-full" :value="meta2dData.name" @change="changeName($event, 'name')" :placeholder="$t('文件名')"></t-input>
          </div>
          <div class="form-item">
            <label>{{$t('分类')}}</label>
            <t-select v-model="data.meta2dData.case" @change="changeValue($event, 'case')">
              <t-option v-for="_case in cases " :value="_case.value" :label="_case.label"> {{ _case.label }} </t-option>
            </t-select>
          </div>
          <t-divider style="margin-left: -16px;width: 120%; " />
          <div class="form-item">
            <label>{{$t('画布尺寸')}}</label>
            <t-input-number label="W" :value="data.meta2dData.width" theme="normal" min="1" style="width: 80px" @change="changeValue($event, 'width')" :placeholder="$t('宽')"></t-input-number>
            <t-input-number class="ml-8" label="H" theme="normal" min="1" :value="data.meta2dData.height" style="width: 80px" @change="changeValue($event, 'height')" :placeholder="$t('高')"></t-input-number>
            <t-dropdown :minColumnWidth="180" :maxHeight="500" :delay2="[10, 150]" overlayClassName="header-dropdown">
              <more-icon class="ml-8 hover"></more-icon>
              <!-- <t-icon name="more" class="ml-8 hover" /> -->
              <t-dropdown-menu>
                <t-dropdown-item
                  v-for="item in screenList"
                  @click="selectedSreen(item)"
                >
                  <div class="flex between">
                    {{ item.name }}
                    <span class="desc">
                      {{ item.width }}
                      <span style="font-size: 10px; margin: 0 4px">x</span>
                      {{ item.height }}
                    </span>
                  </div>
                </t-dropdown-item>
              </t-dropdown-menu>
            </t-dropdown>
          </div>

          <div class="form-item">
            <label>{{$t('背景颜色')}}</label>
            <t-color-picker class="w-full" format="CSS" :recent-colors="null" :enable-alpha="true" :swatch-colors="defaultPureColor" :color-modes="['monochrome']" :show-primary-color-preview="false" v-model="data.meta2dData.background" @change="changeValue($event, 'background')"></t-color-picker>
          </div>
          <div class="form-item">
            <label>{{$t('背景图片')}}</label>
            <t-upload class="ml-8" v-model="data.background" action="/api/image/upload" theme="image" accept="image/*" :headers="headers" :data="updataData" :auto-upload="true" :before-upload="beforeUpload" :upload-all-files-in-one-request="false" @success="fileSuccessed" @remove="fileRemoved"></t-upload>
          </div>
          <div class="form-item">
            <label>{{$t('主题')}}</label>
            <t-select v-model="data.theme" :options="themeOptions" @change="changeTheme" clearable class="shrink-0" :placeholder="$t('暗黑')"></t-select>
          </div>
        </t-space>
        <t-space direction="vertical" size="small" class="mt-8">
          <t-collapse :defaultValue="['1', '2','3']" expandIconPlacement="right" :borderless="true">
            <t-collapse-panel value="1" :header="$t('预览设置')">
              <t-space direction="vertical" size="small">
                <div class="form-item">
                  <label>{{$t('缩放方式')}}</label>
                  <t-radio-group class="ml-8" v-model="data.meta2dData.scaleMode" @change="changeValue($event, 'scaleMode')">
                    <t-radio value="1" style="width: 200px" :title="$t('宽高中较小的铺满')">
                      {{$t('自动铺满')}}
                    </t-radio>
                    <t-radio value="2" style="width: 200px" :title="$t('高度等比例缩放')">
                      {{$t('宽度铺满')}}
                    </t-radio>
                    <t-radio value="3" :title="$t('宽度等比例缩放')">{{$t('高度铺满')}}</t-radio>
                  </t-radio-group>
                </div>
                <div class="form-item">
                  <label>{{$t('显示滚动条')}}</label>
                  <t-checkbox v-model="data.meta2dData.scroll" @change="changeValue($event, 'scroll')" class="ml-8"></t-checkbox>
                </div>
                <div class="form-item">
                  <label>{{$t('禁止移动')}}</label>
                  <t-checkbox v-model="data.meta2dData.isDisableTranslate" @change="changeValue($event, 'isDisableTranslate')" class="ml-8"></t-checkbox>
                </div>
                <div class="form-item">
                  <label>{{$t('禁止缩放')}}</label>
                  <t-checkbox v-model="data.meta2dData.isDisableScale" @change="changeValue($event, 'isDisableScale')" class="ml-8"></t-checkbox>
                </div>
                <!-- <template v-if="data.scroll">
                  <div class="form-item">
                    <label>水平对齐</label>
                    <t-radio-group class="ml-8" default-value="2">
                      <t-radio value="1" style="width: 200px">左对齐</t-radio>
                      <t-radio value="2" style="width: 200px">居中</t-radio>
                      <t-radio value="3" style="width: 200px">右对齐</t-radio>
                    </t-radio-group>
                  </div>
                  <div class="form-item">
                    <label>垂直对齐</label>
                    <t-radio-group class="ml-8" default-value="2">
                      <t-radio value="1" style="width: 200px">顶部对齐</t-radio>
                      <t-radio value="2" style="width: 200px">居中</t-radio>
                      <t-radio value="3" style="width: 200px">底部对齐</t-radio>
                    </t-radio-group>
                  </div>
                </template> -->
              </t-space>
            </t-collapse-panel>
            <t-collapse-panel value="2" :header="$t('进阶设置')">
              <t-space direction="vertical" size="small">
                <div class="form-item">
                  <label>
                    {{$t('图标')}}URL
                    <span>
                      <!-- <label
                        class="vip-label"
                        style="font-size: 10px; padding: 0 2px"
                      >
                        VIP
                      </label> -->
                    </span>
                  </label>
                  <div class="px-8" style="width: 200px">
                    <template v-if="data.meta2dData.iconUrls">
                      <div
                        v-for="(icon, i) of data.meta2dData.iconUrls"
                        class="flex middle between"
                        style="height: 30px"
                      >
                        <div>
                          {{ icon.substring(0, 8) }}...{{ icon.substr(-16) }}
                        </div>
                        <close-icon class="hover"
                          @click="removeIconUrl(i)"/>
                        <!-- <t-icon
                          name="close"
                          class="hover"
                          @click="removeIconUrl(i)"
                        /> -->
                      </div>
                    </template>
                    <div class="flex middle">
                      <t-input v-model="data.iconUrl" style="width: 150px; margin-left: -8px" :placeholder="$t('Font class方式URL')"></t-input>
                      <t-button variant="outline" style="padding: 4px 8px; margin-left: 8px" @click="addIconUrl">
                        {{$t('添加')}}
                      </t-button>
                    </div>
                    <!-- <div v-else class="desc mt-4">
                      支持添加iconfont。
                      <a :href="(getEnterprise as any).account" target="_blank">VIP</a>
                      功能
                    </div> -->
                  </div>
                </div>
                <div class="form-item">
                  <label>{{$t('初始化动作')}}</label>
                  <t-button variant="outline" style="padding: 0 4px; margin: 2px 8px" @click="showInitFnDialog">
                    <ellipsis-icon></ellipsis-icon>
                    <!-- <t-icon name="ellipsis" /> -->
                  </t-button>
                </div>
                <!-- <div class="form-item">
                  <label>数据监听</label>
                  <t-button
                    variant="outline"
                    style="padding: 0 4px; margin: 2px 8px"
                    @click="showDataTransformation"
                  >
                    <ellipsis-icon />
                  </t-button>
                </div> -->
              </t-space>
            </t-collapse-panel>
            <t-collapse-panel value="3" :header="$t('辅助设置')">
              <t-space direction="vertical" size="small">
                <div class="form-item">
                  <label :title="$t('此功能仅对直线和折线有效')">{{$t('连线相交弯曲')}}</label>
                  <t-switch :value="extendData.lineIntersect" class="ml-8 mt-8" size="small" @change="changeLineIntersect"></t-switch>
                </div>
              </t-space>
            </t-collapse-panel>
          </t-collapse>
        </t-space>
      </t-tab-panel>
      <t-tab-panel v-if="isShow" :value="3" :label="$t('行为')">
        <GlobalStates></GlobalStates>
      </t-tab-panel>
      <!-- <t-tab-panel :value="2" label="结构">
        <ElementTree />
      </t-tab-panel> -->
    </t-tabs>
    <t-dialog v-if="initFnDialog.show" :visible="true" @confirm="onOkInitFn" @close="initFnDialog.show = false" :width="700" :header="$t('初始化动作')">
      <CodeEditor v-model="initFnDialog.data" style="height: 300px"></CodeEditor>
    </t-dialog>

    <t-dialog v-if="dataTransformationDialog.show" :visible="true" @confirm="onOkDataTransformation" @close="dataTransformationDialog.show = false" :width="700" :header="$t('数据监听')">
      <CodeEditor v-model="dataTransformationDialog.data" style="height: 300px"></CodeEditor>
    </t-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, onUnmounted, getCurrentInstance } from 'vue';
import { useUser } from '@/services/user';
import { getCookie } from '@/services/cookie';
// import ElementTree from './ElementTree.vue';
import CodeEditor from '@/views/components/common/CodeEditor.vue';
import { autoSave, inTreePanel, useAssets } from '@/services/common';
import { MessagePlugin } from 'tdesign-vue-next';
import { loadCss } from '@meta2d/core';
import { defaultPureColor } from '@/services/defaults';
import { useEnterprise } from '@/services/enterprise';
import { MoreIcon, CloseIcon, EllipsisIcon} from 'tdesign-icons-vue-next';
import { useMeta2dData,useExtendData } from '@/services/common';
import { lineCross,clearLineCross,handleLineCross } from '@meta2d/utils';
import GlobalStates from './GlobalStates.vue';

const { getEnterprise } = useEnterprise();
const { meta2dData, setMeta2dData } = useMeta2dData();
const { extendData, setExtendData } = useExtendData();
const { proxy } = getCurrentInstance();
const $t = proxy.$t
const headers = {
  Authorization: 'Bearer ' + (getCookie('token') || ''),
};
const updataData = { directory: '/大屏/图片/默认' };

// const { assets } = useAssets();

const { user } = useUser();

const isShow = globalThis.globalStates;

const data = reactive<any>({
  tab: 1,
  background: [],
  meta2dData: {},
  iconUrl: '',
});

const cases = [
  {
    label:$t('智慧物联'),
    value:$t('智慧物联')
  },
  {
    label:$t('电力能源'),
    value:$t('电力能源')
  },
  {
    label:$t('智慧水务'),
    value:$t('智慧水务')
  },
  {
    label:$t('智慧工厂'),
    value:$t('智慧工厂')
  },
  {
    label:$t('智慧校园'),
    value:$t('智慧校园')
  },
  {
    label:$t('智慧园区'),
    value:$t('智慧园区')
  },
  {
    label:$t('智慧交通'),
    value:$t('智慧交通')
  },
  {
    label:$t('智慧城市'),
    value:$t('智慧城市')
  },
  {
    label:$t('智慧农业'),
    value:$t('智慧农业')
  },
  {
    label:$t('电信机房'),
    value:$t('电信机房')
  },
  {
    label:$t('航空航天'),
    value:$t('航空航天')
  },
  {
    label:$t('智能家居'),
    value:$t('智能家居')
  }
];

const themeOptions = [
  {
    label: $t('暗黑'),
    value: 'dark',
  },
  {
    label: $t('明亮'),
    value: 'light',
  },
];

const screenList = reactive([
  {
    name: $t('大屏'),
    width: 1920,
    height: 1080,
  },
  {
    name: $t('网页'),
    width: 1440,
    height: 1024,
  },
  {
    name: '平板12.9"',
    width: 1024,
    height: 1366,
  },
  {
    name: '平板11"',
    width: 834,
    height: 1194,
  },
  {
    name: $t('平板Mini'),
    width: 768,
    height: 1024,
  },
  {
    name: $t('华为P8'),
    width: 360,
    height: 640,
  },
  {
    name: $t('华为P40'),
    width: 395,
    height: 856,
  },
  {
    name: $t('手机1'),
    width: 430,
    height: 932,
  },
  {
    name: $t('手机2'),
    width: 375,
    height: 812,
  },
]);

const initFnDialog = reactive<any>({
  show: false,
  data: '',
});

const dataTransformationDialog = reactive<any>({
  show: false,
  data: '',
});

const selectedSreen = (item: any) => {
  meta2d.store.data.width = item.width;
  meta2d.store.data.height = item.height;
  // meta2d.store.patchFlagsBackground = true;
  meta2d.canvas.canvasTemplate.bgPatchFlags = true;
  meta2d.render();
  openData();
};

const beforeUpload = (file: any) => {
  if (!(user && user.id)) {
    MessagePlugin.warning($t('请先登录！'));
    return false;
  }
  return true;
};

const fileSuccessed = async (content: any) => {
  // meta2d.store.patchFlagsBackground = true;
  meta2d.setBackgroundImage(content.response.url);
  setTimeout(() => {
    // meta2d.store.patchFlagsBackground = true;
    meta2d.render();
  }, 1000);
};

const fileRemoved = () => {
  meta2d.setBackgroundImage('');
  // meta2d.store.patchFlagsBackground = true;
  meta2d.render();
  data.background = [];
};
const changeLineIntersect = (e:any)=>{
  setExtendData('lineIntersect',e);
  if(e){
    lineCross(false);
    // handleLineCross(meta2d.store.active.length>0);
  }else{
    clearLineCross();
  }
}
const changeValue = (e: any, key: string) => {
  // @ts-ignore
  meta2d.store.data[key] = e;
  if (key === 'background') {
    // meta2d.store.patchFlagsBackground = true;
    meta2d.setBackgroundColor(e);
  } else if (key === 'width' || key === 'height') {
    meta2d.canvas.canvasTemplate.bgPatchFlags = true;
  }
  meta2d.render();
  openData();
};

const changeTheme = (e)=>{
  meta2d.setTheme(e);
  data.meta2dData.background = meta2d.store.data.background;
}

const changeName = (e: any, key: string) => {
  setMeta2dData({name:e});
};

onMounted(() => {
  if (inTreePanel.value) {
    // data.tab = 2;
  }
  openData();
  meta2d.on('opened', openData);
  meta2d.on('add', finishLine);
  if(extendData.lineIntersect){
    lineCross(true);
  }
});

onUnmounted(() => {
  meta2d.off('opened', openData);
  meta2d.off('add', finishLine);
  setTimeout(()=>{
    clearLineCross();
  },2000);
});

function openData() {
  if (!(meta2d.store.data as any).scaleMode) {
    (meta2d.store.data as any).scaleMode = '1';
  }

  data.meta2dData = Object.assign({}, meta2d.store.data);
  if (meta2d.store.data.bkImage) {
    data.background = [
      {
        name: meta2d.store.data.bkImage,
        url: meta2d.store.data.bkImage,
      },
    ];
  }
}
function finishLine(e) {
  setTimeout(()=>{
    if(e[0].type === 1 && e[0].name === 'line' && ['line',"polyline"].indexOf(e[0].lineName) !== -1){
      extendData.lineIntersect && handleLineCross(meta2d.store.active.length>0);
    }
  },500)
}
const showInitFnDialog = () => {
  initFnDialog.data = meta2d.store.data.initJs;
  initFnDialog.show = true;
};

const onOkInitFn = () => {
  meta2d.store.data.initJs = initFnDialog.data;
  initFnDialog.show = false;
};

const showDataTransformation = () => {
  dataTransformationDialog.data = meta2d.store.data.socketCbJs;
  dataTransformationDialog.show = true;
};

const onOkDataTransformation = () => {
  meta2d.store.data.socketCbJs = dataTransformationDialog.data;
  meta2d.listenSocket();
  dataTransformationDialog.show = false;
};

const addIconUrl = () => {
  if (!data.iconUrl || data.iconUrl.substr(-4) !== '.css') {
    MessagePlugin.error($t('请填写以.css结尾的font-class引用方式的URL地址'));
    return;
  }
  if (!data.meta2dData.iconUrls) {
    data.meta2dData.iconUrls = [];
  }
  data.meta2dData.iconUrls.push(data.iconUrl);
  // @ts-ignore
  meta2d.store.data.iconUrls = data.meta2dData.iconUrls;
  if (meta2d.store.data.iconUrls) {
    for (const item of meta2d.store.data.iconUrls) {
      loadCss(item);
    }
  }
  data.iconUrl = '';
  autoSave(true);
};

const removeIconUrl = (i: number) => {
  data.meta2dData.iconUrls.splice(i, 1);
  // @ts-ignore
  meta2d.store.data.iconUrls = data.meta2dData.iconUrls;
  autoSave(true);
};
</script>
<style lang="postcss" scoped>
.props {
}
</style>
