<template>
  <div v-loading="pageLoading" class="p-6">
    <div class="header">
      <el-page-header @back="jumpBack">
        <template #content>
          <span v-if="mode != 'add'" class="text-large font-600 mr-3"> {{ form.productName }} </span>
        </template>
      </el-page-header>
    </div>

    <!-- <div class="title">
      基本信息
    </div> -->

    <div class="form-data">
      <el-form ref="projectFormRef" :disabled="['examine', 'view'].includes(mode)" :model="form" :rules="formRules" label-width="160">
        <el-row justify="space-evenly">
          <el-col :span="6">
            <el-form-item label="项目编号：" prop="productSn">
              <el-input v-model="form.productSn" placeholder="请输入项目编号" />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="项目名称：" prop="productName">
              <el-input v-model="form.productName" placeholder="此处输入项目名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row justify="space-evenly">
          <el-col :span="6">
            <el-form-item label="项目类型：" prop="productType">
              <el-select v-model="form.productType" clearable placeholder="此处选择项目类型">
                <el-option v-for="dict in project_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="项目规模：" prop="productScale">
              <el-input v-model="form.productScale" min="0" placeholder="此处输入项目规模" type="number">
                <template #append>
                  <span>万</span>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row justify="space-evenly">
          <el-col :span="6">
            <el-form-item label="项目单位：" prop="productUnit">
              <el-input v-model="form.productUnit" :disabled="mode == 'view'" placeholder="请输入项目单位" />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="联系人：" prop="unitBy">
              <el-input v-model="form.unitBy" placeholder="此处输入联系人" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row justify="start">
          <el-col :offset="4" :span="6">
            <el-form-item label="联系电话：" prop="unitConcat">
              <el-input v-model="form.unitConcat" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :offset="4" :span="16">
            <el-form-item label="项目简介：" prop="productBrief">
              <el-input
                v-model="form.productBrief"
                :rows="5"
                maxlength="500"
                placeholder="请输入项目简介,包括项目背景、项目目标、实施计划等。"
                show-word-limit
                type="textarea"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :offset="4" :span="16">
            <el-form-item label="项目立项审批文件：">
              <!-- <span v-if="switchExist" @click="switchMode" class="switch">【切换编辑/查看】</span> -->
              <el-upload
                v-if="mode == 'add'"
                ref="uploadLWRef"
                v-model:file-list="dataInfo.list"
                :action="upload.url"
                :auto-upload="true"
                :headers="upload.headers"
                :limit="10"
                :multiple="multiple"
                :on-remove="handleLWRemove"
                :on-success="handleLWSuccess"
                accept=".xlsx, .xls, .doc, .docx, .txt, .zip, .pdf"
                drag
              >
                <el-icon class="el-icon--upload">
                  <i-ep-upload-filled />
                </el-icon>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <template #tip>
                  <div class="text-center el-upload__tip">
                    <span>支持后缀为 .xls、.xlsx、.doc、.docx、.txt、.zip、.pdf 且大小不超过 200MB的文件，最多上传 10个文件</span>
                  </div>
                </template>
              </el-upload>

              <FileOrImage
                v-for="item in fileList"
                v-else-if="fileList.length"
                :data="item"
                :dataList="[item]"
                :isEdit="false"
                height="100px"
                objectFit="cover"
                width="120px"
              >
              </FileOrImage>

              <el-empty v-else description="暂无数据" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-form
        v-if="(mode === 'view' && approvalStatus != '0') || mode === 'examine'"
        ref="examineFormRef"
        :model="examineForm"
        :rules="examineFormRules"
        label-width="160"
      >
        <el-row>
          <el-col :offset="4" :span="16">
            <el-form-item label="审核结果：" prop="approvalStatus">
              <span v-if="mode === 'view'">{{ ['', '通过', '不通过'][examineForm.approvalStatus] || '-' }}</span>
              <el-radio-group v-else v-model="examineForm.approvalStatus">
                <el-radio label="1" value="1">通过</el-radio>
                <el-radio label="2" value="2">不通过</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="mode === 'view'" label="审核意见：" prop="approvalReason">
              {{ examineForm.approvalReason || '-' }}
            </el-form-item>
            <el-form-item v-else-if="examineForm.approvalStatus == '2'" label="审核意见：" prop="approvalReason">
              <el-input v-model="examineForm.approvalReason" :rows="5" placeholder="请输入审核意见" resize="none" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="form-buttons">
        <el-button v-if="mode == 'examine'" :loading="buttonLoading" type="primary" @click="submitExamineForm">审核</el-button>
        <el-button v-if="!['examine', 'view'].includes(mode)" :loading="buttonLoading" type="primary" @click="submitForm">提交 </el-button>
        <el-button v-if="!['examine', 'view'].includes(mode)" type="danger" @click="cancel">取消</el-button>

        <el-button v-if="['examine', 'view'].includes(mode)" type="info" @click="jumpBack">返回</el-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { Search } from '@element-plus/icons-vue';
import { getProject, addProject, updateProject } from '@/api/project/maintain';
import { ProjectVO, ProjectForm, ProjectQuery } from '@/api/project/maintain/types';
import { getFile } from '@/api/filemanage';
import FileOrImage from '@/components/FileOrImage/index.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { project_type } = toRefs<any>(proxy?.useDict('project_type'));
const multiple = ref(true);
const buttonLoading = ref(false);
const pageLoading = ref(false);
const projectFormRef = ref<ElFormInstance>();
const router = useRouter();
const route = useRoute();
const switchExist = ref(false);
// const switchExist = ref(true);
const modeSwitch = ref(false);
const mode = ref('edit');
const approvalStatus = computed(() => route.query.approvalStatus);
const fileList = ref([]);
const dataInfo = reactive({
  list: [],
  maxLength: 0
});

import { globalHeaders } from '@/utils/request';
import { array } from 'vue-types';

const upload = reactive<UploadOption>({
  headers: globalHeaders(),
  url: import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload'
});
const switchMode = () => {
  modeSwitch.value = !modeSwitch.value;
};
const getFileInfo = async (ids) => {
  let res = await getFile(ids);
  if (res.code != 200) {
    ElNotification({
      title: '提示',
      message: res.msg,
      type: 'error'
    });
    return;
  }
  return res.data;
};
//获取数据
const getData = async (pid) => {
  // console.log(`getData`);
  // console.log(`pid`, pid);

  const res = await getProject(pid).finally(() => {
    pageLoading.value = false;
  });

  if (route.query.mode == 'edit') {
    switchExist.value = true;
  }

  if (res.code == 200) {
    Object.assign(form.value, res.data);
    examineForm.value = {
      approvalStatus: `${res.data.approvalStatus == '0' ? '1' : res.data.approvalStatus}`,
      approvalReason: res.data.approvalReason
    };
    let ossids = res.data.productDataUrl?.split(',') || [];
    fileList.value = ossids;
    if (ossids.length === 0) return;
    let files = await getFileInfo(ossids);
    dataInfo.list = files.map((e) => {
      return {
        name: e.originalName,
        url: e.url
      };
    });
    dataInfo.maxLength = files.length;
    // switchExist.value = true;
    // modeSwitch.value = true;
    return;
  }
};
/** 提交按钮 */
const submitForm = () => {
  pageLoading.value = true;

  // console.log(`status,`,status.value);
  // return

  ElMessageBox.confirm('确认提交以上信息吗', {
    title: '系统确认',
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  })
    .then(() => {
      projectFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
          buttonLoading.value = true;

          //文件
          form.value.productDataUrl = fileList.value.join(',');

          let res;
          if (mode.value == 'edit') {
            res = await updateProject({ ...form.value, approvalStatus: '0', approvalReason: '' }).finally(() => (buttonLoading.value = false));
            if (res.code == 200) {
              proxy?.$modal.msgSuccess('操作成功');

              switchExist.value = false;
              cancel();
            } else {
              ElMessageBox.alert(res.msg, '提示', {
                confirmButtonText: '确定',
                callback: () => {}
              });
            }
          } else if (mode.value == 'add') {
            res = await addProject(form.value).finally(() => (buttonLoading.value = false));

            if (res.code == 200) {
              proxy?.$modal.msgSuccess('操作成功');
              switchExist.value = false;

              cancel();
              // router.replace({ path: '/project/maintain' })
            } else {
              ElMessageBox.alert(res.msg, '提示', {
                confirmButtonText: '确定',
                callback: () => {}
              });
            }
          }
        }
      });
    })
    .catch((err) => {
      console.log(err);
    })
    .finally(() => {
      pageLoading.value = false;
    });
};

const formRules = ref({
  productSn: [{ required: true, message: '项目编号不能为空', trigger: 'blur' }],
  productName: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
  productType: [{ required: true, message: '项目类型不能为空', trigger: 'blur' }],
  productScale: [{ required: true, message: '项目规模不能为空', trigger: 'blur' }],
  productUnit: [{ required: true, message: '项目单位不能为空', trigger: 'blur' }],
  unitBy: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
  unitConcat: [{ required: true, message: '联系电话不能为空', trigger: 'blur' }],
  productBrief: [{ required: true, message: '项目简介不能为空', trigger: 'blur' }]
});

/** 取消按钮 */
const cancel = () => {
  form.value = { ...initForm };
  examineForm.value = {
    approvalStatus: '1',
    approvalReason: ''
  };
  projectFormRef.value?.resetFields();
  proxy?.$tab.closePage(proxy?.$route).then(() => {
    proxy?.$router.replace('/project/maintain');
  });
};

/** 返回 */
const jumpBack = () => {
  proxy?.$tab.closePage(proxy?.$route).then(() => {
    proxy?.$router.replace('/project/maintain');
  });
};

/** 上传成功处理 */
const handleLWSuccess = (response: any, file: UploadFile, uploadFiles: UploadFiles) => {
  if (!fileList.value.some((item) => item == response.data.ossId)) {
    fileList.value.push(response.data.ossId);
  }

  let length = uploadFiles.length;
  dataInfo.maxLength = Math.max(length, dataInfo.maxLength);

  setTimeout(() => {
    if (length !== dataInfo.maxLength) {
      return;
    } else {
      console.log(`触发一次！！！`, dataInfo.list);
      ElMessageBox.alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>',
        '上传项目文件结果',
        {
          dangerouslyUseHTMLString: true
        }
      );
      dataInfo.maxLength = 0;
    }
  }, 10);
};
//删除文件
const handleLWRemove = (uploadFile: UploadFile) => {
  // console.log(`删除.`);
  // console.log(`uploadFile-------`, uploadFile.response.data.url);
  let isExist = fileList.value.indexOf(uploadFile.response.data.ossId);
  if (isExist != -1) {
    fileList.value.splice(isExist, 1);
  }
};

const initForm: ProjectForm = {
  //初始表单
  productSn: '',
  productName: '',
  productType: '',
  productScale: '',
  productUnit: '',
  unitBy: '',
  unitConcat: '',

  productBrief: '',
  productDataUrl: ''
};
const form = ref({ ...initForm });

onActivated(() => {
  if (typeof route.query.mode == 'string') {
    mode.value = route.query.mode;
  } else {
    mode.value = route.query.mode[0];
  }
  if (route.query.mode == 'edit') {
    switchExist.value = true;
    modeSwitch.value = false;
  }
  if (route.query.mode == 'add') {
    form.value = { ...initForm };
    projectFormRef.value?.resetFields();
  }
  if (route.query.id) {
    getData(route.query.id);
  } else {
    dataInfo.list = [];
    dataInfo.maxLength = 0;
  }
});

const examineForm = ref({
  approvalStatus: '1',
  approvalReason: ''
});
const examineFormRules = ref({
  approvalStatus: [{ required: true, message: '请选择审核结果', trigger: 'change' }],
  approvalReason: [{ required: true, message: '请填写审核意见', trigger: 'blur' }]
});

const examineFormRef = ref();
const submitExamineForm = () => {
  // console.log(`status,`,status.value);
  // return
  examineFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      pageLoading.value = true;
      ElMessageBox.confirm('确认提交审核信息吗', {
        title: '系统确认',
        confirmButtonText: '确认',
        cancelButtonText: '取消'
      })
        .then(async () => {
          pageLoading.value = true;
          buttonLoading.value = true;

          const params = { ...form.value, ...examineForm.value };
          let res = await updateProject(params);
          pageLoading.value = false;
          buttonLoading.value = false;

          if (res.code == 200) {
            proxy?.$modal.msgSuccess('操作成功');
            cancel();
            return;
          }
          ElNotification.error({
            title: '提示',
            message: res.msg,
            duration: 3000
          });
        })
        .catch((e) => {
          pageLoading.value = true;
        });
    }
  });
};

onMounted(() => {
  if (typeof route.query.mode == 'string') {
    mode.value = route.query.mode;
  } else {
    mode.value = route.query.mode[0];
  }
  if (route.query.mode == 'edit') {
    switchExist.value = true;
    modeSwitch.value = false;
  }
  if (route.query.mode == 'add') {
    form.value = { ...initForm };
    projectFormRef.value?.resetFields();
  }
  if (route.query.id) {
    getData(route.query.id);
  }
});
</script>

<style lang="scss" scoped>
.p-6 {
  position: relative;
  // padding-bottom: 1vh;
}

:deep(.el-upload) {
  width: 51.5vw;
}

.form-buttons {
  margin: 0 auto;
  width: 20%;
  display: flex;
  justify-content: space-between;
  bottom: 1.5vh;

  .el-button {
    width: 6vw;
  }
}

.switch {
  position: absolute;
  left: -7vw;
  top: 2.2vh;
  color: #36d;
  cursor: pointer;
}

.switch:hover {
  text-decoration: underline;
}

.el-empty {
  margin: 0 auto;
}

.form-data {
  margin-top: 3vh;
}
</style>
