<template>
  <a-layout style="height: 100%; width: 100%">
    <a-layout-content>
      <lt-a-table
        :stripe="true"
        :show-overflow-tooltip="true"
        ref="refTable"
        :search-box="false"
        style="border: 0px; border-left-width: 0px"
        bordered
        :dataSource="showData"
        :footStatus="true"
        :highlight-current-row="true"
        :selectTypeAfterload="selectTypeAfterload"
        :columns="columns"
        :showEditInDialog="false"
        :showToolBar="false"
        size="small"
        :pagination="false"
      >
        <template #headerCell="{ title, column }">
          <template v-if="column.dataIndex === 'ParamName'">
            <em
              class="icon icon-edit"
              style="cursor: pointer; color: dodgerblue"
              :title="$t('LongtecProCessDraw.editInDlg')"
              @click="handleShowDlg"
              v-if="showIcon == true"
            >
            </em>
            {{ title }}
          </template>
        </template>
      </lt-a-table>
    </a-layout-content>
    <a-layout-footer v-if="showOperate == true" class="footerTool">
      <a-button
        type="text"
        title="增加控制参数"
        size="small"
        style="height: 24px; color: green; font-weight: bold"
        @click="handleAddModel"
      >
        <template #icon> <i class="icon icon-plus green"></i> </template
      ></a-button>
      <a-button
        type="text"
        v-if="showData.length > 0"
        title="删除"
        size="small"
        style="height: 24px; color: red"
        @click="handleDel"
      >
        <template #icon> <i class="icon icon-trash red"></i> </template
      ></a-button>
      <a-button
        type="text"
        title="导入模板"
        size="small"
        style="height: 24px; color: green"
        @click="handleImport"
      >
        <template #icon>
          <i class="icon icon-download-alt green"></i>
        </template>
      </a-button>
      <a-button
        type="text"
        title="存为模板"
        size="small"
        style="height: 24px; color: green"
        @click="handleSave"
      >
        <template #icon>
          <i class="icon icon-save green"></i>
        </template>
      </a-button>
      <a-select
        v-model:value="CurDeviceParamaID"
        @change="handleDeviceChange"
        size="small"
        style="width: 200px"
      >
        <a-select-option
          v-for="item in deviceShowOption"
          :key="item.Key"
          :value="item.Key"
          >{{ item.Label }}
        </a-select-option>
      </a-select>
    </a-layout-footer>
  </a-layout>
  <lt-a-model
    v-model:open="visible"
    :title="title"
    :width="600"
    v-model:fullscreen="dlgfullscreen"
    :footer="null"
    :destroyOnClose="true"
    :showSubmitButton="false"
    :showResetButton="false"
  >
    <DlgForm @OnOK="handleDlgOnOK" @OnCancel="handleDlgCancel" />
  </lt-a-model>
  <lt-a-model
    v-model:open="visibleTable"
    title="设备参数"
    :width="800"
    v-model:fullscreen="dlgTablefullscreen"
    :destroyOnClose="true"
    @ok="handleCloseDlg"
  >
    <div
      :style="{
        width: '100%',
        maxHeight: dlgTablefullscreen ? '100%' : '600px',
      }"
    >
      <lt-a-table
        :stripe="true"
        :show-overflow-tooltip="true"
        ref="refTable"
        :search-box="false"
        style="border: 0px; border-left-width: 0px"
        bordered
        :dataSource="showData"
        :footStatus="true"
        :highlight-current-row="true"
        :selectTypeAfterload="selectTypeAfterload"
        :columns="columns"
        :showEditInDialog="false"
        :showToolBar="false"
        size="small"
        :pagination="false"
      >
      </lt-a-table>
    </div>
  </lt-a-model>
</template>

<script setup lang="tsx">
import DlgForm from "../dlg-model/index.vue";
import Api from "../api/api";
import {
  computed,
  ref,
  onMounted,
  reactive,
  watch,
  nextTick,
  PropType,
} from "vue";
import { formatShowCols } from "../../commonMethods/commonMethods";
import type {
  DeviceMainCtrDataStruct,
  DeviceStruct,
  currentDeviceItemStruct,
  DeviceParamaStruct,
  SelectItem,
  ColStruct,
} from "../../../../hooks/type";
import { cloneDeep } from "lodash-es";
const emits = defineEmits(["addModel", "ImportModel"]);

const props = defineProps({
  modelData: {
    type: Object,
    default() {
      return {};
    },
  },
  DeviceModelCols: {
    type: Array as PropType<ColStruct[]>,
    default() {
      return [];
    },
  },
  DevCtlmainColumns: {
    type: Array,
    default() {
      return [];
    },
  },
  DeviceCtlParama: {
    type: Object,
    default() {
      return {};
    },
  },
  showOperate: {
    type: Boolean,
    default: true,
  },
  DevMainCtrData: {
    //控制参数
    type: Array as PropType<DeviceMainCtrDataStruct[]>,
    default() {
      return [];
    },
  },
  planDevice: {
    //设备基础信息
    type: Array as PropType<DeviceStruct[]>,
    default() {
      return [];
    },
  },
  showIcon: {
    type: Boolean,
    default: true,
  },
});
const selectTypeAfterload = 0;
const showData = ref([] as currentDeviceItemStruct[]);
let CurDeviceParamaID = ref(""); //当前选中设备
let DeviceIDS = ref([] as number[]); //所有选中设备
let postModuleData = reactive({
  Items: [] as DeviceParamaStruct[],
});
let originDeviceOption = ref([] as SelectItem[]); //原始设备参数
let DeviceModeName = ref("");
let currentDeviceItem = ref({} as currentDeviceItemStruct);
let ifLoading = ref(false);

const visible = ref(false);
const title = ref("模板名称");
const dlgfullscreen = ref(false);
const visibleTable = ref(false);
const dlgTablefullscreen = ref(false);

const deviceShowOption = ref([] as selectOption[]); //当前下拉选项

const columns = computed(() => {
  //@ts-ignore
  let cols = formatShowCols(props.DeviceModelCols);

  let targetCols = cols.filter((item: any) => {
    return item.dataIndex == "Value";
  });
  if (targetCols.length > 0) {
    //@ts-ignore
    targetCols[0].customRender = ({ record, rowIndex, column }: any) => {
      return _getComTextLabel(record);
    };
  }
  return cols;
});

const handleShowDlg = function () {
  visibleTable.value = true;
};

const handleCloseDlg = function () {
  visibleTable.value = false;
};

const _getComTextLabel = function (record: any) {
  return (
    <a-input
      allowClear
      size="small"
      autofocus={true}
      v-model:value={record.Value}
      onInput={handleValueChange()}
    >
      <template prefix="icon icon-edit">
        <i class="icon icon-edit"></i>
      </template>
    </a-input>
  );
};

const handleValueChange = function () {
  for (let i = 0; i < postModuleData.Items.length; i++) {
    if (
      postModuleData.Items[i].DeviceParamId.toString() ==
      CurDeviceParamaID.value
    ) {
      postModuleData.Items[i].Items = cloneDeep(showData.value);
      break;
    }
  }
};

type selectOption = {
  Key: string;
  Label: string;
};

const showDeviceOption = function () {
  let showArray = [] as selectOption[];

  for (let i = 0; i < DeviceIDS.value.length; i++) {
    for (let j = 0; j < originDeviceOption.value.length; j++) {
      //@ts-ignore
      if (originDeviceOption.value[j].Key == DeviceIDS.value[i]) {
        let temp = {
          Key: DeviceIDS.value[i].toString(),
          //@ts-ignore
          Label: originDeviceOption.value[j].Label,
        };
        const copy = cloneDeep(temp);
        showArray.push(copy);
      }
    }
  }
  deviceShowOption.value = cloneDeep(showArray);

  //return showArray;
};

watch(
  () => props.DeviceCtlParama,
  (newVal) => {
    getDeviceOption();
    nextTick(() => {
      _initShowData();
    });
  },
);

watch(
  () => props.DevMainCtrData,
  (newVal) => {
    getDeviceOption();
    nextTick(() => {
      _initShowData();
    });
  },
);

watch(
  () => props.modelData,
  (Value) => {
    const copy = cloneDeep(Value);
    //@ts-ignore
    showData.value = copy.Items;
    currentDeviceItem.value = copy;
    if (typeof copy.DeviceParamId == "undefined") {
      if (copy.Items.length > 0) {
        copy.DeviceParamId = copy.Items[0].ParamStyleName;
      }
    }
    CurDeviceParamaID.value = copy.DeviceParamId.toString();

    if (postModuleData.Items.length < 1) {
      DeviceIDS.value.push(copy.DeviceParamId);
      //@ts-ignore
      postModuleData.Items.push(copy);
    }
    let bRet = false;
    for (let i = 0; i < postModuleData.Items.length; i++) {
      if (postModuleData.Items[i].DeviceParamId == copy.DeviceParamId) {
        bRet = true;
        //@ts-ignore
        postModuleData.Items[i] = copy;
        break;
      }
    }
    if (!bRet) {
      DeviceIDS.value.push(copy.DeviceParamId);
      //@ts-ignore
      postModuleData.Items.push(copy);
    }
    getDeviceOption();
  },
);

const _initShowData = function () {
  //根据文件中保存的设备参数信息生成界面
  let tempArray = cloneDeep(props.DeviceCtlParama.Items);
  formatShowData(tempArray);
  showData.value = tempArray[0].Items;
  currentDeviceItem.value = tempArray[0];
  CurDeviceParamaID.value = tempArray[0].DeviceParamId.toString();
  for (let j = 0; j < tempArray.length; j++) {
    let copy = cloneDeep(tempArray[j]);
    if (postModuleData.Items.length < 1) {
      DeviceIDS.value.push(copy.DeviceParamId);
      postModuleData.Items.push(copy);
    }
    let bRet = false;
    for (let i = 0; i < postModuleData.Items.length; i++) {
      if (postModuleData.Items[i].DeviceParamId == copy.DeviceParamId) {
        bRet = true;
        postModuleData.Items[i] = copy;
        break;
      }
    }
    if (!bRet) {
      DeviceIDS.value.push(copy.DeviceParamId);
      postModuleData.Items.push(copy);
    }
  }
};

const formatShowData = function (data: any) {
  //因后台没有保存paramaID,因此数据要在前端单独处理 如果ID存在，就使用ID,如果ID不存在，则反向搜索
  if (props.DevMainCtrData.length == 0) {
    return;
  }
  for (let i = 0; i < data.length; i++) {
    if (typeof data[i].DeviceParamId == "undefined") {
      //说明是后台返回的数据，需要反向搜索
      let tempArray = checkReapetItem(data[i]);
      if (tempArray.length > 0) {
        data.splice(i, 1); //先删除当前项，然后把新生成的数据插入进来
        for (let j = 0; j < tempArray.length; j++) {
          data.splice(i, 0, tempArray[j]);
        }
      }
    }
  }
};
const checkReapetItem = function (data: any) {
  let paramaArray = [];
  let paramaName = [data.Items[0].ParamStyleName];
  let temp = {
    DeviceId: data.DeviceId,
    DeviceParamId: getParamaIdByName(data.Items[0].ParamStyleName),
    Items: data.Items.filter((item: any) => {
      return item.ParamStyleName == data.Items[0].ParamStyleName;
    }),
  };
  let copy = {};
  $.extend(true, copy, temp);
  paramaArray.push(copy);
  for (let i = 0; i < data.Items.length - 1; i++) {
    let target = paramaName.filter((item) => {
      return item == data.Items[i].ParamStyleName;
    });
    if (target.length == 0) {
      //说明是新的数据
      paramaName.push(data.Items[i].ParamStyleName);
      let temp = {
        DeviceId: data.DeviceId,
        DeviceParamId: getParamaIdByName(data.Items[i].ParamStyleName),
        Items: data.Items.filter((item: any) => {
          return item.ParamStyleName == data.Items[i].ParamStyleName;
        }),
      };
      let copy = {};
      $.extend(true, copy, temp);
      paramaArray.push(copy);
    }
  }
  return paramaArray;
};
const getParamaIdByName = function (paramaName: string) {
  let id = "";
  let target = props.DevMainCtrData.filter((item: any) => {
    return item.Description == paramaName;
  });
  if (target.length > 0) {
    //@ts-ignore
    id = target[0].DeviceParamId.toString();
  }
  return id;
};
const handleDlgOnOK = function (value: any) {
  DeviceModeName.value = value;
  currentDeviceItem.value.ModelName = value.ModelName;
  let sendData = {
    Items: [] as currentDeviceItemStruct[],
  };
  sendData.Items.push(currentDeviceItem.value);
  ifLoading.value = true;
  Api.SaveDeviceModelParam(sendData)
    .then((data: any) => {
      ifLoading.value = false;
      visible.value = false;
    })
    .catch((err: any) => {
      ifLoading.value = false;
      visible.value = false;
      console.log(err);
    });
};

const handleDlgCancel = function () {
  visible.value = false;
};
const handleDeviceChange = function (id: number) {
  for (let i = 0; i < postModuleData.Items.length; i++) {
    if (postModuleData.Items[i].DeviceParamId == id) {
      showData.value = postModuleData.Items[i].Items;
      currentDeviceItem.value = postModuleData.Items[i];
      break;
    }
  }
};
const getDeviceCtlData = function () {
  //需要提交到后台的数据
  return postModuleData;
};
const handleAddModel = function () {
  //新增模板信息
  // visible.value = true
  emits("addModel", 1);
};
const handleImport = function () {
  //导入模板信息
  emits("ImportModel", 1);
};
const handleSave = function () {
  //存为模板
  visible.value = true;
};
const handleDel = function () {
  //删除当前模板的设备信息
  for (let i = 0; i < postModuleData.Items.length; i++) {
    if (
      postModuleData.Items[i].DeviceParamId.toString() ==
      CurDeviceParamaID.value
    ) {
      postModuleData.Items.splice(i, 1);
      let index = DeviceIDS.value.findIndex(
        (item) => item.toString() === CurDeviceParamaID.value,
      );
      DeviceIDS.value.splice(index, 1);
      if (postModuleData.Items.length == 0) {
        showData.value = [];
        currentDeviceItem.value = {};
        DeviceIDS.value = [];
        break;
      }
      if (i == 0) {
        showData.value = postModuleData.Items[0].Items;
        currentDeviceItem.value = postModuleData.Items[0];
        CurDeviceParamaID.value =
          postModuleData.Items[0].DeviceParamId.toString();
      }
      if (i <= postModuleData.Items.length) {
        showData.value =
          postModuleData.Items[postModuleData.Items.length - 1].Items;
        currentDeviceItem.value =
          postModuleData.Items[postModuleData.Items.length - 1];
        CurDeviceParamaID.value =
          postModuleData.Items[
            postModuleData.Items.length - 1
          ].DeviceParamId.toString();
      }
      break;
    }
  }
};
const getDeviceOption = function () {
  let deviceOption = props.planDevice;
  //console.log("deviceOption", JSON.stringify(deviceOption));
  originDeviceOption.value = [];
  for (let i = 0; i < props.DevMainCtrData.length; i++) {
    let target = deviceOption.filter((item: DeviceStruct) => {
      return item.DeviceId == props.DevMainCtrData[i].DeviceId;
    });
    if (target.length > 0) {
      let name = target[0].DeviceName;
      let temp = {
        Label: "{" + name + "}==" + props.DevMainCtrData[i].Description,
        Key: props.DevMainCtrData[i].DeviceParamId,
      };
      let copy = cloneDeep(temp);
      //@ts-ignore
      originDeviceOption.value.push(copy);
    }
  }

  showDeviceOption();
};

onMounted(() => {
  getDeviceOption();
  if (typeof props.DeviceCtlParama.Items != "undefined") {
    _initShowData();
  }
});

defineExpose({
  getDeviceCtlData,
});
</script>

<style>
.footerTool {
  padding: 5px !important;
  background-color: white !important;
}
</style>
