<!-- @format -->

<template>
  <a-spin :spinning="spinning">
    <div class="ns-skeleton">
      <ns-page-header class="ns-page-header">
        <template #title>
          <div class="title" @click="onBack()">
            <ns-icon name="left" /> <div class="text">配置</div>
          </div>
        </template>
      </ns-page-header>
      <div class="ns-config">
        <div v-for="(configGroup, index) in getConfig" :key="index">
          <a-descriptions style="height: 46px" :style="{ 'margin-top': index ? '16px' : '0px' }">
            <template #title>
              <div class="descriptions-title config-name">
                <span>{{ configGroup.name }}</span>
                <div class="titleFloor"></div>
                <ns-button
                  v-if="paramsValue?.deviceName"
                  style="float: right"
                  type="primary"
                  @click="updateSubmit(paramsValue)"
                  :disabled="!paramsValue"
                  >保存</ns-button
                >
              </div>
            </template>
          </a-descriptions>
          <NsBasicTable
            ref="dataRef"
            :data-source="configGroup.getBindValues"
            :columns="configGroup.columns"
            :pagination="false"
            :rowKey="configGroup.getBindValues.key">
            <template #bodyCell="{ record, column, text }">
              <template v-if="column.dataIndex == 'expectedValue'">
                <!-- //文本编辑 -->
                <div
                  class="editable-cell"
                  v-if="configGroup.getBindValues[record.key - 1].childDataType === 'TEXT'">
                  <!-- 日期组件 -->
                  <div v-if="configGroup.getBindValues[record.key - 1].sign == 'timeRange'">
                    <configDate
                      v-model:timeValue="configGroup.getBindValues[record.key - 1]"
                      :index="index"
                      :listKey="record.key"
                      :text="text"
                      @changeDate="changeData" />
                  </div>
                  <!-- 普通文本 -->
                  <div v-else>
                    <configInput
                      v-model:configValue="configGroup.getBindValues[record.key - 1]"
                      :index="index"
                      :listKey="record.key"
                      @changeInput="changeData" />
                  </div>
                </div>
                <!-- 枚举 -->
                <div
                  v-else-if="
                    configGroup.getBindValues[record.key - 1].childDataType == 'ENUM' ||
                    configGroup.getBindValues[record.key - 1].list?.[0].dataType == 'ENUM'
                  ">
                  <configEnum
                    v-model:configValue="configGroup.getBindValues[record.key - 1]"
                    :index="index"
                    :listKey="record.key"
                    @changeEnum="changeData" />
                </div>
                <!-- 开关 -->
                <div v-else-if="configGroup.getBindValues[record.key - 1].childDataType == 'BOOL'">
                  <configSwitch
                    v-model:configValue="configGroup.getBindValues[record.key - 1]"
                    :index="index"
                    :listKey="record.key"
                    @changeSwitch="changeData" />
                </div>
                <!-- 校验float/int/double -->
                <div
                  v-else-if="
                    configGroup.getBindValues[record.key - 1].childDataType == 'FLOAT' ||
                    'INT' ||
                    'DOUBLE'
                  ">
                  <configInput
                    v-model:configValue="configGroup.getBindValues[record.key - 1]"
                    :index="index"
                    :listKey="record.key"
                    @changeInput="changeData" />
                </div>
                <!-- else -->
                <div v-else> </div>
              </template>
            </template>
          </NsBasicTable>
        </div>
      </div>
    </div>
  </a-spin>
</template>

<script lang="ts">
  import { computed, defineComponent, ref, watch, PropType, UnwrapRef, reactive } from 'vue';
  import { http } from '/nerv-lib/util/http';
  import { useRouter } from 'vue-router';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { message } from 'ant-design-vue';
  import configDate from './configDate.vue';
  import configInput from './configInput.vue';
  import configEnum from './configEnum.vue';
  import configSwitch from './configSwitch.vue';
  import { Handle } from '@antv/x6/lib/addon/common';

  export interface DetailItem {
    label: string;
    name: string;
    value?: string;
    format?: Function;
    type?: string; // 现支持image
  }
  export interface ConfigGroup {
    title: string;
    items: Array<DetailItem>;
  }
  export interface ComponentValueItem {
    configValue: object | string;
    key: number;
    index: number;
  }
  export default defineComponent({
    name: 'NsViewConfig',
    props: {
      config: {
        type: Array as unknown as PropType<ConfigGroup>,
        default: () => [],
      },
      api: {
        type: String,
      },
      updateApi: {
        type: String,
      },
      params: {
        type: Object,
      },
      columns: {
        type: Array,
      },
    },
    // eslint-disable-next-line vue/order-in-components
    components: {
      ExclamationCircleOutlined,
      configDate,
      configInput,
      configEnum,
      configSwitch,
    },
    setup(props) {
      const checked = ref<boolean>(true);
      const tableData = ref([]);
      const router = useRouter();
      const dataRef = ref([]);
      const spinning = ref(false);
      let hasTypeEight = ref();
      let paramsValue = ref();
      //接收子组件传过来的数据并处理
      const changeData = (value: ComponentValueItem) => {
        console.log(value);
        getConfig.value[value.index].getBindValues[value.key - 1].expectedValue = value.configValue;
        if (getConfig.value[value.index].getBindValues[value.key - 1].configItemList) {
          hasTypeEight.value = true;
          getConfig.value[value.index].getBindValues[value.key - 1].configItemList.value =
            value.configValue;
        } else {
          hasTypeEight.value = false;
          getConfig.value[value.index].getBindValues[value.key - 1].itemList.value =
            value.configValue;
        }

        updateConfig(value.index, hasTypeEight.value);
      };
      function request() {
        const { query } = router.currentRoute.value;
        http.get(props.api, query).then((res) => {
          dataRef.value = res.data;
        });
      }
      request();
      //所有类型修改后数据提交
      const updateConfig = (index: number, isTrue) => {
        ///api/objs/Device/ConfigUpdate
        console.log(index);
        console.log(getConfig.value[index].getBindValues);
        let configItemList = [];
        let itemList = [];
        for (const iterator of getConfig.value[index].getBindValues) {
          configItemList.push(iterator.configItemList);
          itemList.push(iterator.itemList);
        }

        let params = {};
        if (isTrue) {
          params = {
            deviceName: props.params.deviceName,
            itemStructList: [
              {
                configItemList: configItemList,
                structIdentifier: getConfig.value[index].identifier,
              },
            ],
            uuid: props.params.uuid,
          };
          paramsValue.value = params;
          return;
        } else {
          params = {
            deviceName: props.params.deviceName,
            itemList: itemList,
            uuid: props.params.uuid,
          };
        }
        updateSubmit(params);

        // http.post(props.updateApi, params).then((res) => {
        //   if (res.code == '200') {
        //     spinning.value = true;
        //     message.success('操作成功');
        //     getConfig;
        //     setTimeout(() => {
        //       request();
        //       spinning.value = false;
        //     }, 3000);
        //   }
        // });

        return 1;
      };
      const updateSubmit = (params) => {
        http.post(props.updateApi, params).then((res) => {
          if (res.code == '200') {
            spinning.value = true;
            message.success('操作成功');
            getConfig;
            setTimeout(() => {
              request();
              spinning.value = false;
            }, 3000);
          }
        });
      };

      //处理后端传过来的数据
      const getConfig = computed(() => {
        if (dataRef.value) {
          return dataRef.value.map((item) => {
            if (!item.dataSpecsList) {
              item.dataSpecsList = item.dataSpecs;
            }
            let bindValues = JSON.parse(item.dataSpecsList);
            if (item.dataType == 4) {
              bindValues = [{ list: bindValues, remark: item.remark, childName: item.name }];
            }
            if (!Array.isArray(bindValues)) {
              bindValues = [
                { childSpecsDTO: bindValues, remark: item.remark, childName: item.name },
              ];
            }
            let i = 1;

            for (const iterator of bindValues) {
              if (
                iterator.childDataType == 'INT' ||
                iterator.childDataType == 'BOOL' ||
                iterator.childDataType == 'ENUM'
              ) {
                if (item.dataType == 8) {
                  iterator.expectedValue = parseInt(iterator.configValue);
                } else {
                  iterator.expectedValue = parseInt(item.expectedValue);
                }
              } else {
                if (item.dataType == 8) {
                  iterator.expectedValue = iterator.configValue;
                } else {
                  iterator.expectedValue = item.expectedValue;
                }
              }

              if (item.dataType == 8) {
                let demo = {
                  identifier: iterator.identifier,
                  value: iterator.expectedValue,
                };
                iterator.configItemList = demo;
              } else {
                let demoCopy = {
                  identifier: item.identifier,
                  value: iterator.expectedValue,
                };
                iterator.itemList = demoCopy;
              }

              iterator.key = i + '';
              i += 1;
            }

            return {
              // title: group.title,
              name: item.name,
              identifier: item.identifier,
              getBindValues: bindValues,
              columns: props.columns,
            };
          });
        }
        return [];
      });
      return {
        getConfig,
        tableData,
        checked,
        updateConfig,
        changeData,
        spinning,
        paramsValue,
        updateSubmit,
      };
    },

    methods: {
      onBack() {
        this.$router.go(-1);
      },
    },
  });
</script>

<style lang="less" scoped>
  :deep(.ant-skeleton-paragraph) {
    display: inline;
    // display: flex;
    // flex-wrap: wrap;
  }

  :deep(.ant-skeleton-paragraph li:nth-child(n)) {
    float: left;
    display: inline;
    margin-right: 130px;
    margin-top: 16px;
    margin-bottom: 4px;
  }

  :deep(.ant-skeleton-paragraph li:nth-child(3n + 1)) {
    clear: both;
    display: inline;
  }

  :deep(.ant-skeleton-content) {
    padding: 0px 8px 10px 10px;
  }

  .ns-detail {
    padding: 0px 8px 10px 10px;
  }

  :deep(.ant-table) {
    border: 1px solid #ededed;
    border-bottom: none;
  }

  :deep(.editable-cell-input-wrapper input) {
    width: 150px;
  }

  :deep(.ant-modal-content) {
    border: 1px solid #dcdfe2;
    box-shadow: none;
  }

  .config-input {
    width: 100px;
  }

  .config-name {
    color: rgba(0, 0, 0, 0.85);
    font-weight: bold;
    font-size: 16px;
    margin: 16px 0;
    height: 30px;
  }

  .config-message {
    color: red;
  }

  .config-message span svg {
    color: red;
  }
  .ns-config {
    padding: 16px;
    border-top: 16px solid #e5ebf0;
    div:first-child {
      .config-name {
        margin-top: 0px;
      }
    }
    :deep(.ns-basic-table) {
      padding-top: 0px;
    }
  }
  // .ns-skeleton .ns-page-header {
  //   margin-bottom: 0 !important;
  // }

  .ns-view {
    min-height: 100%;
    height: 100%;
    background: #e5ebf0;
  }
  :deep(.ant-spin-nested-loading) {
    min-height: 100%;
    height: 100%;
  }
  :deep(.ant-spin-container) {
    min-height: 100%;
    height: 100%;
  }
  :deep(.ant-divider) {
    display: none;
  }
  .ns-page-header {
    margin-bottom: 0 !important;
    padding: 7px 16px !important;
    width: calc(100% + 32px);
    margin-left: -16px;
    .title {
      cursor: pointer;
      font-size: 18px !important;
      display: flex;
      align-items: center;
      .text {
        margin-left: 6px;
      }
    }
  }
  .config-name {
    // span:after {
    //   content: '';
    //   width: 75px;
    //   height: 7px;
    //   display: block;
    //   background: linear-gradient(90deg, @primary-color 0%, #fff 82.67%);
    //   margin-left: 2px;
    //   margin-top: -7px;
    // }
  }
  .ns-add-form {
    border-top: 16px solid #e5ebf0;
    padding: 16px 21px;
    background: #fff;
    height: calc(100% - 47px);
    :deep(.ns-form) {
      .ns-form-item .ns-form-body .ns-child-form-title {
        padding-top: 0;
      }
      &:after {
        display: none;
      }
    }
  }
  :deep(.ns-form.ns-vertical-form) {
    padding-top: 16px !important;
  }
</style>