<template>
  <Dialog
    v-model="visible"
    diaTitle="参数入库"
    :width="'70%'"
    :height="'50%'"
    :zIndex="100"
    @close="handleCloseFun"
    show-footer
  >
    <div class="param-page">
      <BaseTable ref="paramTableRef" tableName="PARAMETER_LIST" hidePagination>
        <template #leftOptions>
          <el-form inline :model="paramFormData">
            <el-form-item label="参数库名称：">
              <el-select
                class="m150"
                v-model="paramFormData.parameterLibraryId"
                @change="libChangeFun"
              >
                <el-option
                  v-for="item in paramLibList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="分类名称：">
              <el-select class="m150" v-model="paramFormData.parameterLibraryCategoryId">
                <el-option
                  v-for="item in paramLibTypeList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="参数对象名称：">
              <el-input v-model="paramFormData.parameterLibraryCategoryObjectName"></el-input>
            </el-form-item>
            <el-form-item label="审核模板">
              <el-select
                class="m150"
                v-model="paramFormData.templateId"
                @change="templateChangeFun"
              >
                <el-option
                  v-for="item in templateList"
                  :key="item.templateId"
                  :value="item.templateId"
                  :label="item.templateName"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </template>
      </BaseTable>
    </div>
    <template #footer>
      <el-button type="" @click="handleCloseFun">关闭</el-button>
      <el-button type="primary" @click="submitFun">入库</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { nextTick, reactive, ref, watch } from 'vue';
import Dialog from '@/components/common/dialog/index.vue';
import BaseTable from '@/components/common/table/baseTable.vue';
import {
  getSimulationParameterTreeApi,
  addLibraryCategoryObjectApi,
} from '@/api/data/simulationParameterLibrary';
import { systemApproveQueryApproveFlowTempalteApi } from '@/api/system/systemApprove';
import { ElMessage } from 'element-plus';
import { cloneDeep } from 'lodash-es';
import { getUserData } from '@/utils/user';
import dayjs from 'dayjs';

const visible = ref(true);
const emits = defineEmits(['close']);

const props = defineProps({
  paramInfo: {
    type: Object,
    default: () => {},
  },
});

const paramFormData = reactive<any>({
  parameterLibraryId: '',
  parameterLibraryCategoryId: '',
  parameterLibraryCategoryObjectName: '新增对象' + new Date().getTime(),
  fileName: '',
  file: '',
  templateId: '',
  templateName: '',
});

const handleCloseFun = () => {
  emits('close');
};

const tableData = ref<any>([]);
const paramTableRef = ref();

const paramLibList = ref<any>([]);
const paramLibTypeList = ref<any>([]);

const getSimulationParameterTreeDAtaFun = async (id?: any) => {
  const param: any = {
    type: 1,
  };

  if (id) {
    param.id = id;
  }

  const res: any = await getSimulationParameterTreeApi(param);
  if (res && res.code === 200) {
    if (id) {
      paramLibTypeList.value = res.data;
    } else {
      paramLibList.value = res.data;
    }
  }
};

const templateList = ref<any>([]);
const queryApproveFlowTempalteFun = async () => {
  const res: any = await systemApproveQueryApproveFlowTempalteApi({});
  if (res && res.code === 200) {
    templateList.value = res.data;
  }
};
const templateChangeFun = () => {
  paramFormData.templateName = templateList.value.find((item: any) => {
    return item.templateId === paramFormData.templateId;
  })?.templateName;
};

const libChangeFun = async () => {
  paramFormData.parameterLibraryCategoryId = '';
  await getSimulationParameterTreeDAtaFun(paramFormData.parameterLibraryId);
};

const submitFun = async () => {
  if (!tableData.value.length) {
    ElMessage.warning('当前不存在参数，无需入库!');
    return;
  }

  const blob = new Blob([JSON.stringify(tableData.value)], { type: 'text/txt' });
  const file = new File([blob], paramFormData.parameterLibraryCategoryObjectName + '.json', {
    type: 'text/plain',
  });
  paramFormData.file = file;
  paramFormData.fileName = paramFormData.parameterLibraryCategoryObjectName + '.json';

  let isNoSubmit: any = false;

  for (const key in paramFormData) {
    if (!paramFormData[key]) {
      isNoSubmit = true;
    }
  }

  if (isNoSubmit) {
    ElMessage.warning('请填写完所有参数再提交！');
    return;
  }

  const res: any = await addLibraryCategoryObjectApi(paramFormData);
  if (res && res.code === 200) {
    ElMessage.success('入库成功!');
    emits('close');
  }
};

watch(
  () => props.paramInfo,
  async (newVal) => {
    if (newVal) {
      tableData.value = cloneDeep(newVal);

      for (let i = 0; i < tableData.value.length; i++) {
        tableData.value[i].createName = await getUserData().nickname;
        tableData.value[i].createTime = dayjs().format('YYYY-MM-DD');
      }

      await getSimulationParameterTreeDAtaFun();
      await queryApproveFlowTempalteFun();
      nextTick(() => {
        paramTableRef.value.setDataFun(tableData.value);
      });
    }
  },
  {
    immediate: true,
    deep: true,
  }
);
</script>

<style lang="scss" scoped>
.param-page {
  width: 100%;

  .el-form-item {
    margin-bottom: 0;
  }

  .m150 {
    width: 150px;
  }
}
</style>
