<template>
  <div>
    <div style="width: 90%;margin: 0 auto ">
      <div style="margin: 8px 0">
        <el-button type="primary" @click="addRequest()">添加</el-button>
      </div>

      <div v-for="(i,k) in requests" style="display: inline-block;margin: 0 8px 8px 0">
        <div v-if="i.type===1" class="textArea" style="width: 400px;height: 200px;display: inline-block">
          <el-card shadow="hover" style="width: 100%;height: 100%" :body-style="{padding: '0'}">
            <div style="margin:8px">
              <div style="width: 100%;height: 50px">
                <div style="width: 50px;height: 100%;display: inline-block">
                  <el-image
                    style="width: 100%; height: 100%;"
                    :src="customizationRequestImg"
                    fit="fill"></el-image>
                </div>
                <div style="width: calc(100% - 50px - 150px);height: 100%;display: inline-block;vertical-align: top">
                  <div style="width: 100%;height: 50%;padding-left: 12px;line-height: 25px;font-weight: 700">
                    <span>
                      {{ i.name || '网络请求' }}
                    </span>
                  </div>
                  <div
                    style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis; width: 175%;height: 50%;padding-left: 12px;line-height: 25px;font-size: 12px;color: #0009">
                    <span>
                      {{ i.url || ' http:10.11.111.111:1111' }}
                    </span>
                  </div>
                </div>
                <div style="width: 150px;height: 100%;display: inline-block;vertical-align: top">
                  <div style="display: flex;justify-content: flex-end;width: 100%">
                    <span style="width: 30px;height: 30px;text-align: center;line-height: 30px;">
                    <i v-if="![0,1,2].includes(i.connectionStatus)" class="el-icon-warning"></i>
                    <i v-if="i.connectionStatus === 0" class="el-icon-loading"
                       style="color:#13c2c2;font-weight: 900"></i>
                    <i v-if="i.connectionStatus === 1" class="el-icon-check" style="color:#ffec3d;font-weight: 900"></i>
                    <i v-if="i.connectionStatus === 2" class="el-icon-close" style="color:#f5222d;font-weight: 900"></i>
                    </span>
                    <el-button style="margin-right: 4px" size="mini" round @click="testConnection(i,k)">测试</el-button>
                    <el-dropdown placement='bottom' trigger="click" @command="dropdownCommand($event,i,k)">
                      <el-button size="mini" round>...</el-button>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item command="del">删除</el-dropdown-item>
                        <el-dropdown-item command="update">修改</el-dropdown-item>
                        <el-dropdown-item command="mapping">设置结果映射</el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </div>
                </div>
              </div>
              <div style="width: 100%;height: 85px;margin-top: 8px">
                <el-tag size="small" v-for="ii in i.params" style="margin: 4px">{{ ii.label }}</el-tag>
                <el-tag size="small" v-if="(i.params||[]).length>12" style="margin: 4px">...</el-tag>
              </div>
              <div style="width: 100%;height: 5px">
                <div style="height: 1px;width: 100%;background-color: #DCDFE6;"></div>
              </div>
              <div style="width: 100%;height: 50px">
                是否启用：
                <el-switch
                  v-model="i.isOpen"
                  active-color="#13ce66"
                  inactive-color="#ff4949">
                </el-switch>
              </div>
            </div>
          </el-card>
        </div>
        <div v-if="i.type===2" class="textArea" style="width: 400px;height: 200px;display: inline-block">
          <el-card shadow="hover" style="width: 100%;height: 100%" :body-style="{padding: '0'}">
            <div style="margin:8px">
              <div style="width: 100%;height: 50px">
                <div style="width: 50px;height: 100%;display: inline-block">
                  <el-image
                    style="width: 100%; height: 100%;"
                    :src="customizationRequestImg"
                    fit="fill"></el-image>
                </div>
                <div style="width: calc(100% - 50px - 150px);height: 100%;display: inline-block;vertical-align: top">
                  <div style="width: 100%;height: 50%;padding-left: 12px;line-height: 25px;font-weight: 700">
                    <span>
                      {{ i.deviceId || '设备' }}
                    </span>
                  </div>
                  <div
                    style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis; width: 175%;height: 50%;padding-left: 12px;line-height: 25px;font-size: 12px;color: #0009">
                    <span>
                      {{ i.functionIdentifier || '属性' }}
                    </span>
                  </div>
                </div>
                <div style="width: 150px;height: 100%;display: inline-block;vertical-align: top">
                  <div style="display: flex;justify-content: flex-end;width: 100%">
                    <span style="width: 30px;height: 30px;text-align: center;line-height: 30px;">
                    <i v-if="![0,1,2].includes(i.connectionStatus)" class="el-icon-warning"></i>
                    <i v-if="i.connectionStatus === 0" class="el-icon-loading"
                       style="color:#13c2c2;font-weight: 900"></i>
                    <i v-if="i.connectionStatus === 1" class="el-icon-check" style="color:#ffec3d;font-weight: 900"></i>
                    <i v-if="i.connectionStatus === 2" class="el-icon-close" style="color:#f5222d;font-weight: 900"></i>
                    </span>
                    <el-button style="margin-right: 4px" size="mini" round @click="testDeviceConnection(i,k)">测试
                    </el-button>
                    <el-dropdown placement='bottom' trigger="click" @command="dropdownDeviceCommand($event,i,k)">
                      <el-button size="mini" round>...</el-button>
                      <template #dropdown>
                        <el-dropdown-menu >
                          <el-dropdown-item command="del">删除</el-dropdown-item>
                          <el-dropdown-item command="update">修改</el-dropdown-item>
                          <el-dropdown-item command="mapping">设置结果映射</el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </div>
              </div>
              <div style="width: 100%;height: 85px;margin-top: 8px">
                <el-tag size="small" v-for="ii in i.params" style="margin: 4px">{{ ii.label }}</el-tag>
                <el-tag size="small" v-if="(i.params||[]).length>12" style="margin: 4px">...</el-tag>
              </div>
              <div style="width: 100%;height: 5px">
                <div style="height: 1px;width: 100%;background-color: #DCDFE6;"></div>
              </div>
              <div style="width: 100%;height: 50px">
                是否启用：
                <el-switch
                  v-model="i.isOpen"
                  active-color="#13ce66"
                  inactive-color="#ff4949">
                </el-switch>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </div>

    <el-dialog
      title="添加请求"
      append-to-body
      v-model="addRequestDialogVisible"
      width="30%">
      <el-row :gutter="12">
        <el-col :span="8">
          <el-card shadow="hover" :body-style="{padding: '0'}">
            <div @click="addNetworkRequest" style="padding:20px">
              <div style="text-align: center">
                <el-image
                  style="width: 100px; height: 100px;"
                  :src="networkImg"
                  fit="fill"></el-image>
              </div>
              <div style="text-align: center">网络请求</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="hover" :body-style="{padding: '0'}">
            <div @click="addEquipment" style="padding:20px">
              <div style="text-align: center">
                <el-image
                  style="width: 100px; height: 100px;"
                  :src="customizationRequestImg"
                  fit="fill"></el-image>
              </div>
              <div style="text-align: center">设备信息</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="hover" :body-style="{padding: '0'}">
            <div @click="addNetworkRequest" style="padding:20px">
              <div style="text-align: center">
                <el-image
                  style="width: 100px; height: 100px;"
                  :src="customizationRequestImg"
                  fit="fill"></el-image>
              </div>
              <div style="text-align: center">自定义请求</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
    <el-button @click="addRequestDialogVisible = false">取 消</el-button>
  </span>
    </el-dialog>

    <el-dialog
      title="网络请求"
      append-to-body
      v-model="addRequestFormDialogVisible"
      width="30%">
      <el-form :model="addRequestForm">
        <InterfaceRequest :form="addRequestForm" />
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="addRequestFormDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addRequestConfirm">确 定</el-button>
  </span>
    </el-dialog>

    <el-dialog
      title="添加设备"
      append-to-body
      v-model="addEquipmentFormDialogVisible"
      width="30%">
      <el-form :model="addEquipmentForm" label-width="120px">
        <EquipmentRequest :form="addEquipmentForm" />
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="addEquipmentFormDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addEquipmentConfirm">确 定</el-button>
  </span>
    </el-dialog>

    <el-dialog title="设置结果映射" v-model="mappingDialogVisible"
               append-to-body width="30%">
      <el-form :model="mappingForm">
        <el-form-item label="pid" v-if="false">
          <el-input v-model="mappingForm.pid" autocomplete="off"></el-input>
        </el-form-item>
        <div v-for="(i,k) in mappingForm.mappingArr">
          <el-form-item label="映射名称" label-width="120px">
            <el-input v-model="i.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="映射字段" label-width="120px">
            <el-cascader
              v-model="i.region"
              :options="options" @change="mappingChange(i,k)"></el-cascader>
          </el-form-item>
          <el-form-item label="将数据某一项集合" v-if="i.isArray">
            <el-select v-model="i.mapData" clearable placeholder="非必选">
              <el-option :label="i.label" :value="i.value" v-for="i in enumOption"></el-option>
            </el-select>
          </el-form-item>
          <div class="add" @click="addMappingArr()">
            <img :src="addIcon" alt="" style="width: 100%">
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="mappingDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="mappingDialogOk">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import addIcon from '@/assets/add.png';
import subtractIcon from '@/assets/subtract.png';
import networkImg from '@/assets/request/network.png';
import customizationRequestImg from '@/assets/request/customizationRequestImg.png';

import InterfaceRequest from './InterfaceRequest';
import EquipmentRequest from './EquipmentRequest';
import { customRequest, interfaceRequest } from '@/components/Configure/networkRequest/requestSend';
import { getHistoryData } from '@/api/configure/configuration/equipment';
import { queryGlobalCfg } from '@/api/configure/configuration/globalCfg.js';


const props = defineProps({
  requests: Object
});

const { requests } = toRefs(props);
const value = ref(false);
const addRequestDialogVisible = ref(false);
const addRequestFormDialogVisible = ref(false);
const addEquipmentFormDialogVisible = ref(false);
const mappingDialogVisible = ref(false);
const addRequestForm = ref({});
const addEquipmentForm = ref({});
const mappingForm = ref({});
const option = ref([]);
const enumOption = ref([]);
const updateFlag = ref(false);
const updateIndex = ref(0);
const updateDeviceFlag = ref(false);
const updateDeviceIndex = ref(0);
const options = ref({});

onMounted(async () => {
  if (!requests.value || !Array.isArray(requests.value)) {
    requests.value = [];
  }
});
const addRequest = () => {
  addRequestDialogVisible.value = true;
};
const addNetworkRequest = () => {
  addRequestFormDialogVisible.value = true;
};
const addEquipment = () => {
  addEquipmentFormDialogVisible.value = true;
};
const addRequestConfirm = () => {
  if (updateFlag.value) {
    requests.value[updateIndex.value] = ({
      ...addRequestForm.value,
      type: 1,
      connectionStatus: -1,
      isOpen: true
    });
  } else {
    requests.value.push(({
      ...addRequestForm.value,
      type: 1,
      connectionStatus: -1,
      isOpen: true
    }));
  }
  updateFlag.value = false;
  addRequestFormDialogVisible.value = false;
  addRequestDialogVisible.value = false;
  addRequestForm.value = {};
};
const addEquipmentConfirm = () => {
  if (updateDeviceFlag.value) {
    requests.value[updateDeviceIndex.value] = {
      ...addEquipmentForm.value,
      type: 2,
      connectionStatus: -1,
      isOpen: true
    };
  } else {
    requests.value.push({
      ...addEquipmentForm.value,
      type: 2,
      connectionStatus: -1,
      isOpen: true
    });
  }
  updateDeviceFlag.value = false;
  addEquipmentFormDialogVisible.value = false;
  addRequestDialogVisible.value = false;
  addEquipmentForm.value = {};
};
const testConnection = (i, k) => {
  requests.value[k]['connectionStatus'] = 0;
  interfaceRequest(i).then(e => {
    requests.value[k]['connectionStatus'] = e.status ? 1 : 2;
    requests.value[k]['request'] = e.data;
  });
};
const testDeviceConnection = (i, k) => {
  requests.value[k]['connectionStatus'] = 0;
  getHistoryData({
    deviceModeId: i.deviceModeId,
    functionIdentifier: i.functionIdentifier + '1',
    interval: i.interval,
    'sceneId': 144,
    'deviceId': i.deviceId,
    startTime: i.startTime,
    endTime: i.endTime,
    intervalType: 1 || i.intervalType
  }).then(e => {
    // this.$set(this.requests[k], 'connectionStatus', e.status ? 1 : 2)
    requests.value[k]['connectionStatus'] = e.code === 200 ? 1 : 2;
    requests.value[k]['request'] = e.data;
  });
};
const dropdownCommand = (command, i, k) => {
  switch (command) {
    case 'del':
      delRequest(i, k);
      break;
    case 'update':
      updateRequestForm(i, k);
      break;
    case 'mapping':
      setMapping(i, k);
      break;
  }
};
const dropdownDeviceCommand = (command, i, k) => {
  switch (command) {
    case 'del':
      delRequest(i, k);
      break;
    case 'update':
      updateDeviceRequestForm(i, k);
      break;
    case 'mapping':
      setDeviceMapping(i, k);
      break;
  }
};
const delRequest = (i, k) => {
  ElMessageBox.confirm('此操作将删除该网络请求, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    requests.value.splice(k, 1);
    ElMessage({
      type: 'success',
      message: '删除成功!'
    });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    });
  });
};
const updateRequestForm = (i, k) => {
  updateFlag.value = true;
  updateIndex.value = k;
  addRequestForm.value = JSON.parse(JSON.stringify(i));
  addRequestFormDialogVisible.value = true;
};
const updateDeviceRequestForm = (i, k) => {
  updateDeviceFlag.value = true;
  updateDeviceIndex.value = k;
  addEquipmentForm.value = JSON.parse(JSON.stringify(i));
  addEquipmentFormDialogVisible.value = true;
};
const setMapping = async (i, k) => {
  if (!requests.value?.[k]?.request) {
    await interfaceRequest(i).then(e => {
      requests.value[k]['connectionStatus'] = e.status ? 1 : 2;
      requests.value[k]['request'] = e.data;
    });
  }
  mappingDialogVisible.value = true;
  // this.mappingForm = {mappingArr:[...(i.mappingForm || {})], pid: k}
  let obj;
  if (!i.mappingForm?.mappingArr || !Array.isArray(i.mappingForm?.mappingArr)) {
    obj = { mappingArr: [i.mappingForm || {}], pid: k };
  } else {
    obj = { mappingArr: i.mappingForm.mappingArr || [], pid: k };
  }
  mappingForm.value = (obj);
  let data = requests.value?.[k]?.request;
  let fun = (v) => {
    return Object.keys(v).map(e => {
      if (v[e].constructor === Object) {
        return {
          value: e,
          label: e,
          type: 'Object',
          children: fun(v[e])
        };
      } else {
        return {
          value: e,
          label: e,
          type: Array.isArray(v[e]) ? 'Array' : 'String',
          enum: Array.isArray(v[e]) ? Object.keys(v[e]?.[0] || {}) : []
        };
      }
    });
  };

  let option1 = fun(data);
  options.value = option1;
  if (mappingForm.value.isArray) {
    mappingChange();
  }
};
const setDeviceMapping = async (i, k) => {
  if (!requests.value?.[k]?.request) {
    await getHistoryData({
      deviceModeId: i.deviceModeId,
      functionIdentifier: i.functionIdentifier + '1',
      interval: i.interval,
      'sceneId': 144,
      'deviceId': i.deviceId,
      startTime: i.startTime,
      endTime: i.endTime,
      intervalType: 1 || i.intervalType
    }).then(e => {
      // this.$set(this.requests[k], 'connectionStatus', e.status ? 1 : 2)
      requests.value[k]['connectionStatus'] = e.code === 200 ? 1 : 2;
      requests.value[k]['request'] = e.data;
    });
  }
  mappingDialogVisible.value = true;
  mappingForm.value = { mappingArr: [(i.mappingForm || {})], pid: k };
  let obj;
  if (!i.mappingForm?.mappingArr || !Array.isArray(i.mappingForm?.mappingArr)) {
    obj = { mappingArr: [(i.mappingForm || {})], pid: k };
  } else {
    obj = { mappingArr: i.mappingForm.mappingArr || [], pid: k };
  }
  mappingForm.value = (obj);
  let data = requests.value?.[k]?.request;
  let fun = (v) => {
    return Object.keys(v).map(e => {
      if (v[e].constructor === Object) {
        return {
          value: e,
          label: e,
          type: 'Object',
          children: fun(v[e])
        };
      } else {
        return {
          value: e,
          label: e,
          type: Array.isArray(v[e]) ? 'Array' : 'String',
          enum: Array.isArray(v[e]) ? Object.keys(v[e]?.[0] || {}) : []
        };
      }
    });
  };

  let option1 = fun(data);
  options.value = option1;
  if (mappingForm.value.isArray) {
    mappingChange();
  }
};
const mappingChange = (e, k) => {
  let data = options.value;
  mappingForm.value.mappingArr[k]?.region.forEach(e => {
    if (Array.isArray(data?.children)) {
      data = data.children?.find(v => v.value === e) || data;
    } else {
      data = data?.find(v => v.value === e) || data;
    }
  });
  mappingForm.value.mappingArr[k]['isArray'] = data.type === 'Array';
  if (mappingForm.value.mappingArr[k].isArray) {
    enumOption.value = data.enum.map(e => {
      return {
        value: e,
        label: e
      };
    });
  } else {
    enumOption.value = [];
  }
};
const mappingDialogOk = () => {
  requests.value[mappingForm.value.pid]['mappingForm'] = mappingForm.value;
  mappingDialogVisible.value = false;
};
const addMappingArr = () => {
  mappingForm.value.mappingArr.push(
    {
      name: '',
      region: '',
      isArray: false,
      mapData: ''
    }
  );
};
</script>


<style>

.add {
  display: inline-block;
  width: 1vw;
  height: 1vw;
  padding: 0.5vw;
  background-color: #409EFF;
  border-radius: 50%;
  cursor: pointer;
}

.subtract {
  display: inline-block;
  width: 1vw;
  height: 1vw;
  padding: 0.5vw;
  background-color: #909399;
  border-radius: 50%;
  cursor: pointer;
}
</style>
