<script setup lang="ts">
import { reactive, onMounted, toRaw, watch } from 'vue';
import useI18n from '@/hooks/useI18n';
import { RESULT_CODE_SUCCESS } from '@/constants/result-constants';
import CodemirrorEditeDiff from '@/components/CodemirrorEditeDiff/index.vue';
import { parseDateToStr } from '@/utils/date-utils';
import {
  getPtNeConfigDataLogList,
  restorePtNeConfigDataLog,
} from '@/api/pt/neConfigDataLog';
import useDictStore from '@/store/modules/dict';
import { message } from 'ant-design-vue';

const { t } = useI18n();
const emit = defineEmits(['ok', 'cancel', 'update:visible']);
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  /**网元类型 */
  neType: {
    type: String,
    default: '',
  },
  /**参数名 */
  paramName: {
    type: String,
    default: '',
  },
  /**学生用户账号 */
  student: {
    type: String,
    default: '',
  },
});

const { getDict } = useDictStore();

/**字典数据 */
let dict: {
  /**业务类型 */
  sysBusinessType: DictType[];
} = reactive({
  sysBusinessType: [],
});

/**对话框对象信息状态类型 */
type StateType = {
  /**新增框或修改框是否显示 */
  visibleByList: boolean;
  /**差异比较框是否显示 */
  visibleByDiff: boolean;
  /**标题 */
  title: string;
  /**加载状态 */
  loading: boolean;
  /**数据 */
  data: Record<string, any>[];
  /**差异数据 */
  dataDiff: Record<string, any>;
  /**确定按钮 loading */
  confirmLoading: boolean;
};

/**对话框对象信息状态 */
let state: StateType = reactive({
  visibleByList: false,
  visibleByDiff: false,
  title: '操作参数名称-学生账号',
  loading: false,
  data: [],
  dataDiff: {},
  confirmLoading: false,
});

function onClose() {
  state.loading = false;
  state.visibleByList = false;
  state.visibleByDiff = false;
  state.data = [];
  state.dataDiff = {};
  emit('cancel');
  emit('update:visible', false);
  queryParams = {
    neType: '',
    paramName: '',
    student: '',
    pageNum: 1,
    pageSize: 10,
  };
}

/**查询参数 */
let queryParams = reactive({
  /**网元类型 */
  neType: '',
  /**可用属性值 */
  paramName: '',
  /**学生账号 */
  student: '',
  /**当前页数 */
  pageNum: 1,
  /**每页条数 */
  pageSize: 10,
});

/**查询列表, pageNum初始页数 */
function fnGetList(pageNum?: number) {
  if (state.loading) return;
  state.loading = true;
  if (pageNum) {
    queryParams.pageNum = pageNum;
    if (pageNum === 1) state.data = [];
  }
  getPtNeConfigDataLogList(toRaw(queryParams)).then(res => {
    if (res.code === RESULT_CODE_SUCCESS && Array.isArray(res.rows)) {
      // tablePagination.total = res.total;
      state.data = state.data.concat(res.rows);
      // 去首个做标题
      if (queryParams.pageNum === 1 && state.data.length > 0) {
        const item = state.data[0];
        state.title = `${item.paramDisplay} - ${item.createBy}`;
      }
      if (state.data.length <= res.total && res.rows.length > 0) {
        queryParams.pageNum++;
      }
    }
    state.loading = false;
  });
}

/**差异比较框打开 */
function fnMergeCellOpen(row: Record<string, any>) {
  state.dataDiff = row;
  state.dataDiff.paramJsonOld = JSON.stringify(
    JSON.parse(state.dataDiff.paramJsonOld),
    null,
    2
  );
  state.dataDiff.paramJsonNew = JSON.stringify(
    JSON.parse(state.dataDiff.paramJsonNew),
    null,
    2
  );
  state.visibleByDiff = true;
}

/**差异比较框关闭 */
function fnMergeCellClose() {
  state.visibleByDiff = false;
  state.dataDiff = {};
}

/**差异比较还原 */
function fnMergeCellRestore(value: 'old' | 'new') {
  if (state.confirmLoading) return;
  const id = state.dataDiff.id;
  restorePtNeConfigDataLog({ id, value })
    .then((res: any) => {
      if (res.code === RESULT_CODE_SUCCESS) {
        message.success({
          content: t('common.operateOk'),
          duration: 3,
        });
        fnMergeCellClose();
        fnGetList(1);
      } else {
        message.error({
          content: `${res.msg}`,
          duration: 3,
        });
      }
    })
    .finally(() => {
      state.confirmLoading = false;
    });
}

/**监听是否显示，初始数据 */
watch(
  () => props.visible,
  val => {
    if (val) {
      if (props.neType && props.paramName) {
        state.title = '';
        state.visibleByList = true;
        // 根据条件查询数据
        queryParams.neType = props.neType;
        queryParams.paramName = props.paramName;
        if (props.student) {
          queryParams.student = props.student;
        }
        fnGetList();
      }
    }
  }
);

onMounted(() => {
  // 初始字典数据
  Promise.allSettled([getDict('sys_oper_type')]).then(resArr => {
    if (resArr[0].status === 'fulfilled') {
      dict.sysBusinessType = resArr[0].value;
    }
  });
});
</script>

<template>
  <div>
    <a-drawer
      :width="500"
      :title="state.title"
      placement="right"
      :visible="state.visibleByList"
      @close="onClose"
    >
      <a-list
        class="demo-loadmore-list"
        item-layout="horizontal"
        :data-source="state.data"
      >
        <template #loadMore>
          <div
            :style="{
              textAlign: 'center',
              marginTop: '12px',
              height: '32px',
              lineHeight: '32px',
            }"
          >
            <a-button @click="fnGetList()" :loading="state.loading">
              {{ t('views.configManage.configParamForm.ptDiffLoad') }}
            </a-button>
          </div>
        </template>
        <template #renderItem="{ item }">
          <a-list-item>
            <template #actions>
              <a-tooltip>
                <template #title>
                  {{ t('views.configManage.configParamForm.ptDiffMerge') }}
                </template>
                <a-button type="primary" @click.prevent="fnMergeCellOpen(item)">
                  <template #icon><MergeCellsOutlined /></template>
                </a-button>
              </a-tooltip>
            </template>
            <a-list-item-meta>
              <template #title>
                <DictTag
                  :options="dict.sysBusinessType"
                  :value="item.operaType"
                />
              </template>
              <template #description>
                {{ parseDateToStr(item.createTime) }}
              </template>
            </a-list-item-meta>
          </a-list-item>
        </template>
      </a-list>
    </a-drawer>

    <a-modal
      :width="800"
      :destroyOnClose="true"
      :mask-closable="false"
      v-model:visible="state.visibleByDiff"
      :footer="null"
      :body-style="{ padding: 0, maxHeight: '650px', 'overflow-y': 'auto' }"
      @ok="fnMergeCellClose()"
      @cancel="fnMergeCellClose()"
    >
      <template #title>
        <DictTag
          :options="dict.sysBusinessType"
          :value="state.dataDiff.operaType"
        />
        {{ parseDateToStr(state.dataDiff.createTime) }}
      </template>
      <div class="diffBack">
        <div>
          <a-button
            type="text"
            :loading="state.confirmLoading"
            @click.prevent="fnMergeCellRestore('old')"
          >
            <template #icon><MergeCellsOutlined /></template>
            {{ t('views.configManage.configParamForm.ptDiffRest') }}
          </a-button>
        </div>
        <div>
          <a-button
            type="text"
            :loading="state.confirmLoading"
            @click.prevent="fnMergeCellRestore('new')"
          >
            <template #icon><MergeCellsOutlined /></template>
            {{ t('views.configManage.configParamForm.ptDiffRest') }}
          </a-button>
        </div>
      </div>
      <CodemirrorEditeDiff
        :old-area="state.dataDiff.paramJsonOld"
        :new-area="state.dataDiff.paramJsonNew"
      ></CodemirrorEditeDiff>
    </a-modal>
  </div>
</template>

<style lang="less" scoped>
.diffBack {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  & > div:first-child {
    flex: 1;
    background: #fa9;
  }
  & > div:last-child {
    flex: 1;
    background: #8f8;
  }
}
</style>
