<template>
  <header>
    <Navbar title="数据归档" :is-go-back="true" />
    <label>业务名称：</label>
    <a-select
      v-model:value="selectValue"
      style="width: 200px"
      :disabled="isDisabled"
      :options="businessNames"
      @change="nameChange"
    />
    <a-divider />
  </header>
  <div v-if="selectValue">
    <div class="queryParams">
      <ul class="ulStyle">
        <li v-for="(item, index) in allParams" :key="index" class="liStyle">
          <label> {{ item.viewName }}：</label>
          <span v-if="item.displayType == 'DateTimeBoxEditor'">
            <a-date-picker
              v-model:value="item.dateValue"
              show-time
              :locale="locale"
              class="commonWidth"
              @change="
                (_, dateString) => dateChange(_, dateString, item.paramName)
              "
            />
          </span>
          <span v-if="item.displayType == 'TextEditor'">
            <a-input
              v-model:value="item.defaultValue"
              class="commonWidth"
              @change="(e) => textChange(e, item.paramName)"
            />
          </span>
          <span v-if="item.displayType == 'NumberEditor'">
            <a-input-number
              v-model:value="item.defaultValue"
              class="commonWidth"
              :min="0"
              @change="(value) => numberChange(value, item.paramName)"
            />
          </span>
          <span v-if="item.displayType == 'CheckBoxEditor'">
            <a-checkbox
              v-model:checked="item.defaultValue"
              @change="(e) => checkChange(e, item.paramName)"
            />
          </span>
        </li>
      </ul>
    </div>
    <a-divider />
    <a-button type="primary" @click="startArchive">执行归档</a-button>
    <a-result
      v-if="isShow"
      status="success"
      :title="`${businessName}业务归档成功`"
    >
      <template #subTitle>
        <div>共创建了{{ createCount }}个可视数据</div>
        <div style="text-align: left; margin-left: 36%">
          <div v-for="(item, index) in tableMessages" :key="index">
            {{ index + 1 }}、{{ item.tableName }}表成功归档{{
              item.successExporterCount
            }}条，删除{{ item.deleteSuccessCount }}条
          </div>
        </div>
      </template>
      <template #extra>
        <a-button type="primary" @click="isShow = false">关闭</a-button>
        <a-button @click="checkData">查看归档数据</a-button>
      </template>
    </a-result>
    <Loading v-if="loading" />
  </div>
  <!-- <a-button
    v-if="isDisabled"
    type="primary"
    style="margin-top: 36px; width: 88px"
    @click="goBack"
  >
    上一步
  </a-button> -->
</template>

<script setup>
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import { ref, reactive, onMounted } from 'vue';
import Common from '../common/Common';
import { message } from 'ant-design-vue';
import { getBusinessName, getBusinessParams, execute } from './config';
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN';
import { useRoute, useRouter } from 'vue-router';

dayjs.locale('zh-cn');
const selectValue = ref('');
const businessName = ref(''); //业务名
const archiveLogId = ref(''); //下载路径
const isShow = ref(false);
const tableMessages = ref([]); //表
const createCount = ref(''); //创建的可视数据个数
const businessNames = ref([]); // 业务名数据
const allParams = ref([]);
const archiveParams = reactive({});
const loading = ref(false);
const route = useRoute();
const router = useRouter();
const isDisabled = ref(false);

onMounted(() => {
  const {
    query: { businessName: businessNameParam },
  } = route;
  if (businessNameParam) {
    isDisabled.value = true;
    selectValue.value = businessNameParam;
    businessName.value = businessNameParam;
    nameChange({}, { name: '' }, true);
  } else {
    getName();
  }
});
// const goBack = () => {
//   router.back();
// };
// 获取时间类型值
const dateChange = (_, dateString, paramName) => {
  archiveParams[paramName] = dateString;
};
// 获取文本框类型值
const textChange = (e, paramName) => {
  archiveParams[paramName] = e.target.value;
};
// 获取数字框类型值
const numberChange = (value, paramName) => {
  archiveParams[paramName] = value;
};
// 获取Boolean类型值
const checkChange = (e, paramName) => {
  archiveParams[paramName] = e.target.checked;
};
// 获取业务名
const getName = () => {
  loading.value = true;
  getBusinessName().then(
    success => {
      loading.value = false;
      if (success.errorCode == 0) {
        if (success.datas) {
          success.datas.forEach(item => {
            item.value = item.name;
            item.label = item.name;
          });
          businessNames.value = success.datas;
        }
      } else {
        message.error(success.errorMessage);
      }
    },
    error => {
      loading.value = false;
      Common.processException(error);
    },
  );
};
// 获取业务参数
const nameChange = (_, { name }, flag) => {
  loading.value = true;
  let nameParam;
  if (flag) {
    nameParam = businessName.value;
  } else {
    nameParam = name;
    businessName.value = name;
  }
  getBusinessParams(nameParam).then(
    ({ errorCode, datas, errorMessage }) => {
      loading.value = false;
      if (errorCode == 0) {
        if (datas) {
          datas.forEach(item => {
            if (item.displayType == 'DateTimeBoxEditor') {
              item.dateValue = dayjs(item.defaultValue, 'YYYY-MM-DD HH:mm:ss');
            }
            archiveParams[item.paramName] = item.defaultValue;
          });
          allParams.value = datas;
        }
      } else {
        message.error(errorMessage);
      }
    },
    error => {
      loading.value = false;
      Common.processException(error);
    },
  );
};

// 开始执行
const startArchive = () => {
  loading.value = true;
  const params = {
    businessName: businessName.value,
    archiveParams,
  };
  execute(params).then(
    success => {
      loading.value = false;
      if (success.errorCode == 0) {
        if (success.data) {
          isShow.value = true;
          archiveLogId.value = success.data.archiveLogId;
          tableMessages.value = success.data.archiveParams.tableMessages;
          createCount.value =
            success.data.archiveParams.visualizationFileNames.length;
        }
      } else {
        message.error(success.errorMessage);
      }
    },
    error => {
      loading.value = false;
      Common.processException(error);
    },
  );
};
// 查看归档数据
const checkData = () => {
  loading.value = true;
  const fileUrl = encodeURIComponent(archiveLogId.value);
  const xhr = new XMLHttpRequest();
  xhr.open(
    'get',
    `api/ArchivesResource/download?archiveLogId=${fileUrl}`,
    true,
  );
  const token = localStorage.getItem('#token');
  xhr.setRequestHeader('token', token);
  xhr.setRequestHeader('Content-type', 'application/json');
  xhr.responseType = 'blob';
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
      loading.value = false;
      let res = xhr.response;
      let blob = new Blob([res]);
      const blobUrl = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.download = '可视数据.zip';
      link.style.display = 'none';
      link.href = blobUrl;
      document.body.appendChild(link);
      link.click();
      URL.revokeObjectURL(blobUrl);
      document.body.removeChild(link);
      message.success('下载成功');
    } else {
      loading.value = false;
    }
  };
  xhr.send();
};
</script>

<style scoped>
:deep(.ant-divider.ant-divider-horizontal) {
  margin: 8px 0 !important;
}
.commonWidth {
  width: 200px;
}
.ulStyle {
  width: 100%;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}
.liStyle {
  width: 25%;
  margin-top: 8px;
}
</style>