<template>
  <a-modal class="customs_dialog" :open="dialogVisible" :cancel="handleClose" title="小水库批量填报" >
    <div class="upload_div">
      <a-upload-dragger
        :multiple="false"
        :action="actionUrl"
        :file-list="fileList"
        @change="handleSuccess"
        ref="upload"
        class="upload-demo">
        <p class="ant-upload-drag-icon">
          <a-icon type="inbox" />
        </p>
        <p class="ant-upload-text">
          将模板文件拖到此处，或<em>点击选取模板文件</em>
        </p>
      </a-upload-dragger>
      <a-button type="primary" @click="submitUpload" :loading="uploadLoading">点击上传</a-button>
    </div>
    <div ref="messageDiv" id="messageDiv" style="width: 100%;margin-top: 10px">
      <!-- 验证数据的弹出框 -->
      <shuiKuTianbaoPlVer
        v-if="showShuiKuTianBaoPlVer"
        @closePlVerDialog="closePlVerDialog"
        :tableData="tableData"
        :uuid="uuid"
        :id="id"></shuiKuTianbaoPlVer>
      <a type="primary" @click="openPlVerDialog" href="javascript:void(0)" v-show="showButton">点击弹框</a>
    </div>
  </a-modal>
</template>

<script>
import request from '../../utils/gw_ajax_request.js';
import shuiKuTianbaoPlVer from './shuiKuTianbao_piliang_verify';
export default {
  props: ['showShuiKuTianBaoPl', 'id'],
  components: {
    shuiKuTianbaoPlVer: shuiKuTianbaoPlVer,
  },
  data() {
    return {
      dialogVisible: true,
      fileList: [],
      uuid: 1,
      actionUrl: '',
      socket: null,
      showShuiKuTianBaoPlVer: false,
      filePath: '',
      tableData: [],
      showButton: false,
      uploadLoading: false,
    };
  },
  computed: {
    persId() {
      return localStorage.getItem('persId')
        ? localStorage.getItem('persId')
        : '1098101939614724096';
    },
  },
  created() {},
  methods: {
    handleClose(done) {
      this.closeSocket();
      this.$parent.getSkDataList();
      this.$emit('closePlDialog');
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`,
      );
    },
    beforeRemove(file, fileList) {
      // return this.$confirm(`确定移除 ${ file.name }？`);
    },
    beforeAvatarUpload(file) {
      const Xls = file.name.split('.');
      if (Xls[1] === 'xls') {
        return file;
      } else {
        this.$message.error('请上传编辑后的模板文件!');
        return false;
      }
    },
    handleSuccess(res, file, fileList) {
      const filePath = res.data.key;
      this.filePath = filePath;
      // 调用解析的接口
      request
        .get(
          `/dc/impExcel/parseExcel/${this.persId}/${this.uuid}?filePath=${this.filePath}&tid=08&pid=${this.id}`,
        )
        .then((res) => {
          this.tableData = res.data;
          console.log('table:' + this.tableData);

          if (this.tableData.length > 0) {
            this.showButton = true;
            this.showShuiKuTianBaoPlVer = true;
          } else {
            this.$alert('可填报数据条数为0或非本组数据，请确认！', '提示', {
              confirmButtonText: '确定',
              type: 'warning',
              callback: (action) => {},
            });
          }
          // 只展示错误数据的逻辑
          // if(this.tableData[0].Message == undefined){
          //     this.showButton = true;
          //     this.showShuiKuTianBaoPlVer = true;
          // }else{
          //     var message = this.tableData[0].Message;
          //     if(message == 'success'){
          //         this.showButton = true;
          //         this.showShuiKuTianBaoPlVer = true;
          //     }else {
          //         this.$alert('可填报数据条数为0或非本组数据，请确认！', '提示', {
          //             confirmButtonText: '确定',
          //             type: 'warning',
          //             callback: action => {

          //             }
          //         });
          //     }
          // }

          this.uploadLoading = false;
        });
    },
    openSocket() {
      if (typeof WebSocket === 'undefined') {
        console.log('您的浏览器不支持WebSocket');
      } else {
        this.closeSocket();
        console.log('您的浏览器支持WebSocket');
        console.log('sid:' + this.uuid);
        // 实例化WebSocket对象，指定要连接的服务器地址与端口  建立连接
        // let baseUrl = "localhost:8101";
        // 测试服务器
        const baseUrl = '10.1.102.136:8100';
        // let baseUrl = "sv.goldenwater.com.cn";
        // let baseUrl = "localhost:8085/wsbackend";
        this.socket = new WebSocket(`ws://${baseUrl}/websocket/${this.uuid}`);

        // socket
        const socket = this.socket;
        // 打开事件
        socket.onopen = () => {
          console.log('Socket 已打开');
          // socket.send("这是来自客户端的消息" + location.href + new Date());
        };
        // 获得消息事件
        socket.onmessage = (msg) => {
          console.log(msg.data);
          document.getElementById('messageDiv').innerHTML =
            document.getElementById('messageDiv').innerHTML +
            msg.data +
            '<br/>';
          // 发现消息进入    开始处理前端触发逻辑
          if (msg.data.indexOf('完成数据校验') > 0) {
          }
        };
        // 关闭事件
        socket.onclose = () => {
          console.log('Socket已关闭');
        };
        // 发生了错误事件
        socket.onerror = () => {
          console.log('Socket发生了错误');
          // 此时可以尝试刷新页面
        };
        // 路由跳转时结束websocket链接
        this.$router.afterEach(() => {
          socket.close();
        });
      }
    },
    getUUID() {
      request.get('/socket/uuid').then((res) => {
        if (res.success) {
          this.uuid = res.data.key;
          this.actionUrl = `/modular-source/6ace62b8e2bb467d98286d260aebcef2/pdcApi/dc/impExcel/imp/${this.persId}/${this.uuid}?tid=08`;
        } else {
          console.log('success不为true');
        }
      });
    },
    closeSocket() {
      if (this.socket != null) {
        this.socket.close();
      }
    },
    submitUpload() {
      this.uploadLoading = true;

      // 获取uuid
      const p1 = new Promise((resolve) => {
        resolve(
          request({
            url: `/socket/uuid`,
            method: 'get',
          }),
        );
      });

      Promise.all([p1])
        .then((result) => {
          if (result) {
            //
            const data = result[0];
            const uuid = data.data.key;
            this.uuid = uuid;
            // console.log(this.uuid);
            // this.actionUrl = `/pdcApi/dc/impExcel/imp/${this.persId}/${this.uuid}?tid=08`;
            this.actionUrl = `/modular-source/6ace62b8e2bb467d98286d260aebcef2/pdcApi/dc/impExcel/uploadExcel/${this.persId}/${this.uuid}?tid=08`;
            this.openSocket();
          }
        })
        .then(() => {
          this.$refs.messageDiv.innerHTML = '';

          this.$refs.upload.submit();
        });
    },
    closePlVerDialog() {
      this.showShuiKuTianBaoPlVer = false;
    },
    openPlVerDialog() {
      this.showShuiKuTianBaoPlVer = true;
    },
  },
};
</script>

<style lang='less' scoped>

</style>
