<template>
  <div style="padding: 0 30px;">
    <el-button type="primary" style="position: absolute;right: 100px;z-index: 9999;" @click="formSubmit()">{{readonly ? '编辑' : '保存'}}</el-button>
    <el-button v-if="!readonly" style="position: absolute;right: 20px;z-index: 9999;" @click="formSubmit('-1')">取消</el-button>
    <Form ref="formRef" :formList="formList" :ruleFormData="ruleForm" :config="{labelWidth: '140px', buttonGroup: []}" @fnClick="callback">
      <template #tempPoeConfigRules="{ field, model, formModel }">
        <div v-if="!readonly">
          <template v-if="formModel && formModel.pppoeConfigMode === '1'">
            <el-upload
              class="disInlineBlock mr20"
              action=""
              :auto-upload="false"
              :on-change="handleFileUpload"
              accept=".xls, .xlsx, .numbers"
              :show-file-list="false">
              <el-button size="mini" type="primary">导入</el-button>
            </el-upload>
            <el-button type="info" size="mini" @click="downloadTemp">模板下载</el-button>
          </template>
          <div style="margin-left: -120px">
            <TableList id="tabHeadCenter" ref="tabRef" :columns="columns" :config="config" :queryParams="{total: 0}" :tableList="roleList"  @fnClick="callback">
              <template #tempEditModel="{ row, valueKey, column }">
                <el-input-number v-if="column.type === 'number'" v-model="row[valueKey]" :disabled="formModel.pppoeConfigMode === '2' ? column.editShow === '2' ? false : true : false"
                                 class="w100" :controls="false" :min="column.min || undefined" :max="column.max || undefined"  size="small" :placeholder="column.placeholder || ''" />
                <el-input v-else v-model="row[valueKey]" class="w100" size="small"  :disabled="formModel.pppoeConfigMode === '2' ? column.editShow === '2' ? false : true : false"
                          :placeholder="column.placeholder" />
              </template>
            </TableList>
          </div>
        </div>
        <div v-else style="margin-left: -120px">
          <TableList ref="tabRef" :columns="columns" :config="{colHiddenCheck: true, colTopHiddenIcon: true}" :queryParams="{total: 0}" :tableList="roleList">
            <template #tempStatus="{ valueKey, row, column }">
              <span v-if="row[valueKey] === '0'">未连通</span>
              <span v-if="row[valueKey] === '1'">已连通</span>
            </template>
          </TableList>
        </div>
      </template>
    </Form>
  </div>
</template>

<script>
  import * as XLSX from 'xlsx';
  import Form from '@/components/form/index.vue';
  import TableList from '@/components/table/index.vue';
  import {networkList, addPoeConfigMain} from '@/api/disRevenue/resource';
  export default {
    name: "PPPoEConfig",
    components: {Form, TableList},
    dicts: ['pppoe_enabled', 'pppoe_config_mode'],
    props: {
      modelVal: {
        type: Array,
        default: () => []
      }
    },
    watch: {
      modelVal: {
        handler(val, oldVal) {
          if (val && val.length > 0) {
            val[0].pppoeEnabled = val[0] && (val[0].pppoeEnabled || val[0].pppoeEnabled === 0) ? val[0].pppoeEnabled.toString() : val[0].pppoeEnabled;
            let newModel = JSON.parse(JSON.stringify(val));
            this.ruleForm = newModel[0];
            newModel[0].subList.map((item,index) => {
               item['targetIndexNum'] = index + 1;
              if (index !== 0) {
                item['showNum'] = '1';
              }
            });
            this.readonly = true;
            this.roleList = JSON.parse(JSON.stringify(newModel[0].subList));
            this.fnFormList(this.readonly);
            this.poeInterfaceList();
          }
        },
        deep: true,
        immediate: true
      },
    },
    data() {
      return {
        ruleForm: {},
        formList: [],
        readonly: true,
        contentList: [{oneNum: '',ipv4Addr: '', ipv4Num: '', ipv4Graw: ''}],
        roleList: [],
        columns: {},
        config: {},
        ipList: [],
        loadingBool: false,
      }
    },
    created() {
    },
    methods: {
      // formList集合
      fnFormList(readonly) {
        this.formList = [{
          config: {title: '', labelWidth: '140px', readonly: readonly},
          controls: {
            id: {label: 'ID', hidden: true},
            clientId: {label: 'clientId', hidden: true},
            pppoeEnabled: {label: '启用PPPoE', span: readonly ? 12 : 24, type: 'radio', options: this.dict.type.pppoe_enabled, required: true},
            pppoeConfigMode: {label: 'PPPoE配置方式', span: readonly ? 10 : 24, type: 'select', eventName: 'change', options: this.dict.type.pppoe_config_mode, warningTitle: '使用multi_wan_conntrack.sh', required: true},
            pppoeInterface: {label: 'PPPoE网卡', span: readonly ? 12 : 24, type: 'select', options: this.ipList || [], required: true, hidden: this.ruleForm.pppoeConfigMode === '1' ? false: true,},
            subList: {label: 'PPPoE配置规则', span: 24, slotName: 'tempPoeConfigRules'},
          }
        }];
        this.columns = {
          id: { label: `ID`,width: '50'},
          serialNumber: { label: `序号`, minWidth: '50',visible: true, type: 'number', placeholder: '请输入', slotName: readonly ? null : 'tempEditModel'},
          vlanId: { label: `VLANID`, minWidth: '80',visible: true, type: 'number', placeholder: '请输入数字', slotName: readonly ? null : 'tempEditModel'},
          ipv4Address: { label: `IPv4地址`, minWidth: '100',visible: true, placeholder: '如1.1.1.1', slotName: readonly ? null : 'tempEditModel'},
          ipv4MaskBits: { label: `IPv4掩码位数`, minWidth: '100',visible: true, type: 'number', min: 1, max: 32, placeholder: '请输入1-32', slotName: readonly ? null : 'tempEditModel'},
          ipv4Gateway:{ label: `IPv4网关`,minWidth: '100',visible: true, placeholder: '如1.1.1.1', slotName: readonly ? null : 'tempEditModel'},
          bandwidthResult: { label: `虚拟网卡上报带宽(Mbps)`, minWidth: '170', visible: true, editShow: '2', placeholder: '请输入', slotName: readonly ? null : 'tempEditModel'},
          macAddress: { label: `MAC地址`, minWidth: '120', visible: readonly},
          inSpeed: { label: `下载速度(Mbps)`, minWidth: '120', visible: readonly},
          outSpeed: { label: `上传速度(Mbps)`, minWidth: '120', visible: readonly},
          totalInSpeed: { label: `已接收流量(GB)`, minWidth: '120', visible: readonly},
          totalOutSpeed: { label: `已发送流量(GB)`, minWidth: '120', visible: readonly},
          netRunTime: { label: `拨号时长`, minWidth: '80', visible: readonly},
          status: { label: `连通状态`, minWidth: '80', slotName: 'tempStatus', visible: readonly},
        };
        if (!readonly && this.ruleForm.pppoeConfigMode === '1') {
          this.config = {
            colHiddenCheck: true, colTopHiddenIcon: true,
              tableButton: {
              line: [
                {content: '新增', fnCode: 'add', type: 'text'},
                {content: '删除', fnCode: 'delete', type: 'text', showName: 'showNum', showVal: '1'},
              ]
            }
          };
        } else {
          this.config = {colHiddenCheck: true, colTopHiddenIcon: true}
        }
      },
      poeInterfaceList() {
        if (this.loadingBool) return;
        this.loadingBool = true;
        networkList({clientIds: this.ruleForm.clientId, newFlag: 1}).then(res => {
          this.ipList = [];
          res && res.data.map(item => {
            this.ipList.push({label: item.interfaceName, value: item.interfaceName});
          });
          this.formList[0].controls.pppoeInterface['options'] = this.ipList;
          this.loadingBool = false;
        });
      },
      // 切换编辑和保存
      formSubmit(num) {
        if (num === '-1') {
          // 1. 获取表单引用
          const formRef = this.$refs.formRef;
          // 2. 先清除所有表单校验
          if (formRef && formRef.$refs.ruleForm) {
            formRef.$refs.ruleForm.clearValidate(); // 清除校验提示
          }
          // 3. 重置为只读模式
          this.readonly = true;
          this.fnFormList(this.readonly);
          // 4. 恢复原始数据（而不是清空）
          if (this.modelVal && this.modelVal[0]) {
            // 深度复制原始数据
            const originalData = JSON.parse(JSON.stringify(this.modelVal[0]));
            // 将 pppoeEnabled 转换为字符串（如果需要）
            if (originalData.pppoeEnabled || originalData.pppoeEnabled === 0) {
              originalData.pppoeEnabled = originalData.pppoeEnabled.toString();
            }
            this.ruleForm = originalData;
          } else {
            // 如果没有原始数据，重置为空对象
            this.ruleForm = {};
          }
          // 5. 重置表格数据
          if (this.modelVal && this.modelVal[0] && this.modelVal[0].subList) {
            this.roleList = JSON.parse(JSON.stringify(this.modelVal[0].subList));
            this.roleList.forEach((item, index) => {
              item.targetIndexNum = index + 1;
              if (index !== 0) {
                item.showNum = '1';
              }
            });
          } else {
            this.roleList = [];
          }
        } else {
          if (!this.readonly) {
            this.ruleForm = Object.assign({}, this.ruleForm, this.$refs.formRef.$refs.ruleForm.model);
            this.submitPoeModel();
          } else {
            this.ruleForm = Object.assign({}, this.ruleForm, {typeName: 111});
            this.roleList = this.roleList.length > 0 ? this.roleList : [{targetIndexNum: 1, serialNumber: 1, vlanId: undefined, ipv4Address: undefined, ipv4MaskBits: undefined, ipv4Gateway: undefined, bandwidthResult: undefined}];
            if (this.ruleForm && this.ruleForm.pppoeConfigMode == '2') {
              this.roleList = this.roleList.length > 0 ? this.roleList : [];
            }
            this.readonly = !this.readonly;
            this.fnFormList(this.readonly);
          }
        }
      },
      // form验证
      fnFormValid() {
        return new Promise((resolve) => {
          this.ruleForm = {};
          const formValid = this.$refs.formRef.$refs.ruleForm;
          // 3. 操作form（如验证）
          formValid.validate((valid) => {
            if (valid) {
              this.ruleForm = formValid.model;
              resolve(true);
            } else {
              resolve(false);
            }
          });
        });
      },
      // 新增判断
      async submitPoeModel() {
        let formValidateBool = true;
        if (this.ruleForm.pppoeEnabled && this.ruleForm.pppoeEnabled === '1') {
          if (!await this.fnFormValid()) {
            formValidateBool = false;
          }
        } else {
          this.$refs.formRef.$refs.ruleForm.clearValidate(); // 清除校验提示
        }
        if (!formValidateBool) return;
        let params = {
          clientId: this.ruleForm.clientId,
          pppoeEnabled: this.ruleForm.pppoeEnabled,
          pppoeConfigMode: this.ruleForm.pppoeConfigMode,
          pppoeInterface: this.ruleForm.pppoeInterface,
          subList: this.roleList
        };
        let indexNum = 0;
        if (this.modelVal && this.modelVal[0] && this.modelVal[0].subList && this.modelVal[0].subList.length === this.roleList.length) {
          let arr = ['vlanId', 'serialNumber', 'ipv4Address', 'ipv4MaskBits', 'ipv4Gateway', 'bandwidthResult'];
          Object.keys(params).some(keyName => {
            if (keyName ==='subList') {
              params['subList'].some((item,index) => {
                arr.some(keyTowName => {
                  if (item[keyTowName] !== this.modelVal[0].subList[index][keyTowName]) {
                    indexNum = 1;
                    return true;
                  }
                });
                return true;
              });
            } else if (params[keyName] !== this.modelVal[0][keyName]) {
              indexNum = 1;
            }
          });
        } else {
          indexNum = 1;
        }
        if (indexNum === 0) {
          this.readonly = true;
          this.fnFormList(this.readonly);
          return;
        }
        addPoeConfigMain(params).then(res => {
          this.$emit('poeDataChange');
          // this.ruleForm = Object.assign(this.ruleForm, this.$refs.formRef.$refs.ruleForm.model, {typeName: 222});
          // this.readonly = true;
          // this.fnFormList(this.readonly);
        });
      },
      // 监听事件
      callback(result, dataVal, formVal) {
        if (result && result.fnCode) {
          switch (result.fnCode) {
            case 'add':
                this.roleList.push({targetIndexNum: this.roleList.length + 1,showNum: '1', serialNumber: 1, vlanId: undefined, ipv4Address: undefined, ipv4MaskBits: undefined, ipv4Gateway: undefined, bandwidthResult: undefined});
              break;
            case 'delete':
              this.roleList.splice(this.roleList.findIndex(item => item.targetIndexNum === dataVal.targetIndexNum), 1);
              break;
            case 'pppoeConfigMode':
              if (dataVal === '1') {
                this.formList[0].controls.pppoeInterface['hidden'] = false;
                let newModel = JSON.parse(JSON.stringify(this.modelVal));
                newModel[0].subList.map((item,index) => {
                  item['targetIndexNum'] = index + 1;
                  if (index !== 0) {
                    item['showNum'] = '1';
                  }
                });
                this.roleList = newModel[0].subList.length > 0 ? newModel[0].subList : [{targetIndexNum: 1, serialNumber: 1, vlanId: undefined, ipv4Address: undefined, ipv4MaskBits: undefined, ipv4Gateway: undefined, bandwidthResult: undefined}];
                this.config = {
                  colHiddenCheck: true, colTopHiddenIcon: true,
                    tableButton: {
                    line: [
                      {content: '新增', fnCode: 'add', type: 'text'},
                      {content: '删除', fnCode: 'delete', type: 'text', showName: 'showNum', showVal: '1'},
                    ]
                  }
                };
              } else if (dataVal === '2') {
                if (this.modelVal[0].pppoeConfigMode && this.modelVal[0].pppoeConfigMode.toString() === '2') {
                  let newModel = JSON.parse(JSON.stringify(this.modelVal));
                  newModel[0].subList.map((item,index) => {
                    item['targetIndexNum'] = index + 1;
                    if (index !== 0) {
                      item['showNum'] = '1';
                    }
                  });
                  this.roleList = newModel[0].subList;
                } else {
                  this.roleList = [];
                }
                this.formList[0].controls.pppoeInterface['hidden'] = true;
                this.config = {
                  colHiddenCheck: true, colTopHiddenIcon: true,
                };
              }
              break;
            default:
          }
        }
      },
      downloadTemp() {
        const link = document.createElement('a');
        link.href = 'http://172.16.15.51:9300/statics/csvfile/macvlan_vlan.csv';
        link.download = 'macvlan_vlan.csv';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      },
      handleFileUpload(file) {
        // 如果是使用 Element UI 的 el-upload 组件，文件对象是 file.raw
        const actualFile = file.raw || file; // 兼容两种获取方式[1,3](@ref)
        if (!actualFile) {
          return;
        }
        const fileReader = new FileReader();
        fileReader.onload = (e) => {
          try {
            // 1. 获取读取结果，并将其转换为 Uint8Array
            const data = new Uint8Array(e.target.result);
            // 2. 使用 xlsx 解析数据
            const workbook = XLSX.read(data, { type: 'array' });
            // 3. 获取第一个工作表（Sheet）的名称
            const firstSheetName = workbook.SheetNames[0];
            // 4. 根据工作表名称获取对应的工作表对象
            const worksheet = workbook.Sheets[firstSheetName];
            // 5. 将工作表数据转换为 JSON 格式
            // header: 1 表示按数组格式解析，包含表头；默认按对象格式（第一行为键名）
            const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
            // 或者使用对象格式（更常用，第一行作为对象的键）[3,6](@ref)
            // const jsonData = XLSX.utils.sheet_to_json(worksheet);

            // 6. 将解析后的数据存储在组件的 data 中
            // this.excelData = jsonData;
            // console.log('解析到的Excel数据：', jsonData);

            // 可以在这里调用后续处理方法，如数据校验、发送到后端等
            this.processExcelData(jsonData);

          } catch (error) {
            // console.error('解析Excel文件时出错：', error);
            this.$message.error('文件解析失败，请检查文件格式是否正确。');
          }
        };

        fileReader.onerror = (error) => {
          this.$message.error('读取文件失败，请重试。');
        };
        // 开始以 ArrayBuffer 格式读取文件
        fileReader.readAsArrayBuffer(actualFile);
      },
      processExcelData(data) {
        // 在这里对解析出的数据进行进一步处理
        // 例如：数据清洗、验证、转换格式等[2](@ref)
        if (data.length > 0) {
          let oldDataList = this.oldTableList();
          let arrList = [];
          data.map((item,index) => {
            if (item && item.length > 0) {
              let arr = ['vlanId', 'serialNumber', 'ipv4Address', 'ipv4MaskBits', 'ipv4Gateway', 'bandwidthResult'];
              let obj = {targetIndexNum: oldDataList.length + index + 1, showNum: '1'};
              arr.forEach((val, valIndex) => {
                obj[val] = item[valIndex];
              });
              arrList.push(obj);
            }
          });
          this.roleList = oldDataList.concat(arrList);
        } else {
          this.$message.warning('导入的文件中没有数据。');
        }
      },
      oldTableList() {
        let contentList = [];
        this.roleList.forEach(item => {
          let indexNum = 0;
          Object.keys(item).some(val => {
            if (val !== 'serialNumber' && val !== 'targetIndexNum' && val !== 'showNum' && item[val]) {
              indexNum = 1;
              return;
            }
          });
          if (indexNum === 1) {
            contentList.push(item);
          }
        });
        return contentList;
      },
    }
  }
</script>

<style scoped>
  ::v-deep #tabHeadCenter .el-table .el-table__header-wrapper th, .el-table .el-table__fixed-header-wrapper th {
   text-align: center!important;
 }
</style>
