<template>
  <div id="ProblemList">
    <h-row :gutter="24">
      <div class="tops list">
        {{ t('ImpExp.common.Hint') }} {{ t('ImpExp.common.Total') }} {{ props.rowData.dataCount }}
        {{ t('ImpExp.common.data') }}{{ t('ImpExp.common.AbnormalDataList') }}
        <div class="color-red">{{ props.rowData.errCount }}</div>
        {{ t('ImpExp.common.Strip') }}
      </div>
    </h-row>
    <h-row :gutter="25">
      <div class="list table-list">
        <div>
          <div class="red"></div>
          {{ t('ImpExp.common.DataList') }}
        </div>
        <div>
          <h-button v-if="props.errOption == 1" style="margin-right: 18px" @click="neglect">
            {{ t('ImpExp.common.IgnoreAll') }}
          </h-button>
          <h-button v-if="props.errOption == 1" @click="update">
            {{ t('ImpExp.common.UpdateAll') }}
          </h-button>
        </div>
      </div>
      <div class="DataList" style="max-height: 500px">
        <!-- 1:用户确认 2:终止 3:忽略 -->
        <h-b-table
          v-if="props.errOption != '1'"
          id="guide-queryTable"
          v-bind="tableProps"
          rowKey="id"
          :needRowIndex="true"
          :show-size="false"
          :showExport="false"
          :animateRows="false"
          :rowSelection="false"
          :ref="handleTbaleRef"
          :pagination="false"
          :scroll="{
            extra: 24,
            y: 500,
          }"
        ></h-b-table>
        <h-b-table
          v-if="props.errOption == '1'"
          id="guide-queryTable"
          v-bind="tableProps"
          rowKey="id"
          :needRowIndex="true"
          :show-size="false"
          :showExport="false"
          :animateRows="false"
          :ref="handleTbaleRef"
          :rowSelection="false"
          :pagination="false"
          :scroll="{
            extra: 24,
            y: 500,
          }"
        >
          <template #option="{ record }">
            <h-radio-group v-model:value="record.option">
              <h-radio :value="2" @click="err(record)">{{ t('ImpExp.common.Ignore') }}</h-radio>
              <h-radio :value="1" @click="err(record)" v-if="record.EID">
                {{ t('ImpExp.common.Update') }}
              </h-radio>
            </h-radio-group>
          </template>
        </h-b-table>
      </div>
    </h-row>
    <h-row style="margin: 24px -10px -15px">
      <h-col :span="24" style="text-align: right">
        <h-button @click="cancelClick" style="margin-right: 20px">
          {{ t('ImpExp.common.Cancel') }}
        </h-button>
        <h-button style="margin-right: 20px" @click="downLoad">
          {{ t('ImpExp.common.DownloadEXCEL') }}
        </h-button>
        <h-button
          v-if="props.errOption == '3'"
          @click="handleOk"
          style="background-color: #4a556bff; color: #fff"
          :loading="loading"
        >
          {{ t('ImpExp.common.ConfirmImp') }}
        </h-button>
        <h-button v-if="props.errOption == '2'" disabled>
          {{ t('ImpExp.common.ConfirmImp') }}
        </h-button>
        <h-button
          v-if="props.errOption == '1' && userState != 0"
          @click="handleOk"
          style="background-color: #4a556bff; color: #fff"
          :loading="loading"
        >
          {{ t('ImpExp.common.ConfirmImp') }}
        </h-button>
        <h-button v-if="props.errOption == '1' && userState == 0" disabled>
          {{ t('ImpExp.common.ConfirmImp') }}
        </h-button>
      </h-col>
    </h-row>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, ref, watchEffect } from 'vue';
import { commonApi } from '@remote/icpx-platform/commonApi';
/* import { commonApi } from '@/api/commonApi/index'; */
import { useButtonGroup, useTable } from '@crami/bui-platform';
import { getInfo, ICP_CONFIG } from '@remote/icpx-platform/utils';
/* import { getInfo, ICP_CONFIG } from '@/utils/commMethods'; */
import { importErrListAPI, ExpDataAPI } from '@/api/platform/ImpExp/Import';
import { downloadUrlAPI } from '@/api/platform/ImpExp/upload';
import { message } from '@crami/ui';
import { useI18n } from '@crami/locale';

export default defineComponent({
  name: 'ProblemList',
  props: ['rowData', 'userIds', 'dataCaches', 'dataList', 'errOption'],
  setup(props, { emit }) {
    // 多语言
    const { t } = useI18n();
    const loading = ref<boolean>(false);

    const commonParams = computed(() => {
      return getInfo(ICP_CONFIG);
    });
    // console.log(commonParams);

    const [menuRef, menuProps, { getRowMenu }] = useButtonGroup({
      sortRule: 'default',
      pageName: 'ProblemList',
      dataSourceApi: {
        url: commonApi().studioCache.getMetaInfo.url,
        params: {
          ...commonApi().studioCache.getMetaInfo.params,
          ...{
            type: 'menuv2',
            name: commonParams.value?.menuName,
          },
        },
        method: commonApi().studioCache.getMetaInfo.method,
      },
    });
    const [menuRefTable, menuPropsTable, { load }] = useButtonGroup({
      sortRule: 'computedByNumber',
      computedByNumber: 3,
      pageName: 'ProblemList',
      items: [],
      moreItem: {
        trigger: ['click'],
      },
    });
    //处理行内操作按钮
    watchEffect(async () => {
      const rowData = getRowMenu('link');
      load(rowData);
    });
    const [gridRef, tableProps, tableMethods] = useTable({
      // 表头数据
      // initialLoad: false,
      configApi: {
        url: commonApi().system.getData.url,
        method: commonApi().system.getData.method,
        params: {
          type: 'gridTitle',
          data: {
            ...commonApi().system.getData.params,
            viewName: 'P_SYS_IMPORT_CHECK_LISTVIEW',
          },
        },
      },
      // 数据接口
      dataSourceApi: {
        url: '/api/importservice/import/getCheckData',
        method: 'post',
        params: {
          // ...props.dataList,
          dataCache: props.dataCaches, //可以为空
          // companyId: commonParams.value.companyId,
          // connect: commonParams.value.connect,
          // lang: commonParams.value.lang,
          // userId: props.userIds,
        },
      },
      beforeRequest: (type, params: any) => {
        if (type == 'column') {
          if (params && params.data) {
            params.data = JSON.stringify(params.data);
          }
        }
        return {
          ...params,
        };
      },
      afterRequest: (type, params: any) => {
        if (type == 'column' && props.errOption == '1') {
          params.columns.push({
            title: t('ImpExp.common.UserComfirm'),
            dataIndex: 'option',
            show: true,
            showMode: null,
            sorter: true,
            width: 200,
          });
        }
        if (type == 'data') {
          params.data.forEach((item, index) => {
            // 判断当前数据是否有eid返回
            if (item.eid == null) {
              item.eid = null;
            } else {
              item.ied = item.eid.value;
            }
            // 当errOption值为3(忽略)时，给option附上默认值
            if (props.errOption == '3') {
              item.option = 2;
            }
            item.id = index;
          });
          params.total = params.data.length;
        }
      },
      columnExtra: {
        option: {
          customSlot: 'option',
          sorter: false,
        },
        SHEETNAME: {
          sorter: false,
        },
        LOCATION: {
          sorter: false,
        },
        ERRMSG: {
          sorter: false,
        },
      },
    });
    const handleTbaleRef = (el: any) => {
      gridRef.value = el;
    };

    const dataList = JSON.parse(localStorage.getItem('data'));
    console.log(JSON.parse(localStorage.getItem('dataImp')));

    // 点击确定时关闭弹窗
    const handleOk = async () => {
      loading.value = false;

      // 判断用户确认列是否全部选中
      let result = tableProps.dataSource.every(item => {
        if (!item.option) {
          return false;
        } else {
          return true;
        }
      });
      if (!result) {
        // result为false时代表有数据未选中
        message.warning('用户确认列为必选项');
        return;
      } else {
        // 过滤数据，将需要的字段传给后端
        let errDataList = [];
        tableProps.dataSource.forEach(item => {
          errDataList.push({
            EID: item.EID,
            SHEETNAME: item.SHEETNAME,
            OPTION: item.option,
            ROWINDEX: item.ROWINDEX,
          });
        });

        // 保存操作过的数据;
        await importErrListAPI({
          ...dataList, //编码 导入按钮上默认配置
          dataCache: props.dataCaches, //数据缓存key
          customValid: errDataList,
          companyId: commonParams.value.companyId,
          connect: commonParams.value.connect,
          userId: commonParams.value.user_id,
          lang: commonParams.value.lang,
          ecode: JSON.parse(localStorage.getItem('dataImp')).ecode,
        }).then(res => {
          // console.log(res);
          if (res.code == 200) {
            fileId.value = res.data.fileId;
            message.success(t('ImpExp.common.ImpSucceed'));
            emit('startUsing');
            cancelClick();
            loading.value = false;
          } else {
            message.warning(res.msg);
            return;
          }
        });
      }
    };
    const fileId = ref();
    // 点击关闭时关闭弹窗
    const cancelClick = () => {
      emit('cancelClick');
    };

    const userState = ref(0);
    let newArr = [];
    const err = record => {
      newArr.push(record);
      userState.value = null;
    };

    // 点击修改为全部忽略
    const neglect = () => {
      tableProps.dataSource.forEach(item => {
        item.option = 2;
      });
      userState.value = null;
    };
    // 点击修改为全部更新
    const update = () => {
      tableProps.dataSource.forEach(item => {
        item.option = 1;
      });
      userState.value = null;
    };
    // 点击时下载excel文件
    const downLoad = () => {
      ExpDataAPI({
        companyId: commonParams.value.companyId,
        connect: commonParams.value.connect,
        lang: commonParams.value.lang,
        objectType: '',
        dataRoute: 'http://platform-base-importservice/import/getCheckData',
        dataCache: props.dataCaches,
        // viewName: commonParams.value.listViewName,
        viewName: 'P_SYS_IMPORT_CHECK_LISTVIEW',
        isAll: 'all',
        eids: [],
      }).then(res => {
        if (res.code == 200) {
          downloadUrlAPI(res.data.fileIds)
            .then(res => {
              var xz = new XMLHttpRequest();
              console.log(xz);
              xz.open('GET', res.data.templateUrl, true);
              xz.responseType = 'blob';
              xz.onload = function (e) {
                // console.log(e);
                var url = window.URL.createObjectURL(xz.response);
                var a = document.createElement('a');
                a.href = url;
                a.download = res.data.fileName;
                a.click();
              };
              xz.send();
            })
            .catch();
        } else {
          message.warning(res.msg);
          return;
        }
      });
    };

    return {
      t,
      loading,
      newArr,
      downLoad,
      err,
      cancelClick,
      props,
      gridRef,
      tableProps,
      tableMethods,
      neglect,
      update,

      handleOk,

      handleTbaleRef,

      menuRef,
      menuProps,
      menuRefTable,
      menuPropsTable,
      userState,
    };
  },
});
</script>

<style lang="less" scoped>
.red {
  width: 3px;
  height: 15px;
  display: inline-block;
  margin: -3px 4px 0;
  background-color: red;
  vertical-align: middle;
}
.color-red {
  color: red;
}
.btn {
  color: #898989;
  border: 1px solid rgb(43, 41, 41);
}
.list {
  margin: 0 0 5px;
  font-size: 16px;
  width: 100%;
}
.table-list {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.tops {
  margin-top: -10px;
  display: flex;
}
.DataList {
  width: 100%;
  padding: 8px 12px;
}
.col {
  font-size: 14px;
  color: #898989;
  margin: 5px 0;
}
.data {
  transform: translateY(145px);
}
</style>
