<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="110px">
            <el-form-item label="申请单编号" prop="formNo">
              <el-input v-model="queryParams.formNo" placeholder="请输入申请单编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="工程名称" prop="projectName">
              <el-input v-model="queryParams.projectName" placeholder="请输入工程名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="提出单位" prop="submitUnit">
              <el-input v-model="queryParams.submitUnit" placeholder="请输入提出单位" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="专业" prop="specialty">
              <el-input v-model="queryParams.specialty" placeholder="请输入专业" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="提出日期" prop="submitDate">
              <el-date-picker clearable v-model="queryParams.submitDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择提出日期" />
            </el-form-item>
            <el-form-item label="卷册名称" prop="volumeName">
              <el-input v-model="queryParams.volumeName" placeholder="请输入卷册名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="卷册号" prop="volumeNo">
              <el-input v-model="queryParams.volumeNo" placeholder="请输入卷册号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['design:designChange:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['design:designChange:remove']"
              >删除</el-button
            >
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="loading" :data="designChangeList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="申请单编号" align="center" prop="formNo" />
        <el-table-column label="工程名称" align="center" prop="projectName" />
        <el-table-column label="提出单位" align="center" prop="submitUnit" />
        <el-table-column label="专业" align="center" prop="specialty" />
        <el-table-column label="提出日期" align="center" prop="submitDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.submitDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="卷册名称" align="center" prop="volumeName" />
        <el-table-column label="卷册号" align="center" prop="volumeNo" />
        <el-table-column label="变更原因" align="center" prop="changeReason">
          <template #default="scope">
            <dict-tag :options="design_change_reason_type" :value="scope.row.changeReason ? scope.row.changeReason.split(',') : []" />
          </template>
        </el-table-column>
        <el-table-column label="变更内容" align="center" prop="changeContent" />
        <!-- <el-table-column label="变更费用估算" align="center" prop="costEstimation" /> -->
        <el-table-column label="变更文件" align="center" prop="fileId">
          <template #default="scope">
            <span  style="color: rgb(41 145 255);cursor: pointer" @click="onOpen(scope.row.file.originalName)"> {{ scope.row.file.originalName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="查看" placement="top">
              <el-button link type="primary" icon="View" @click="handleView(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['design:designChange:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['design:designChange:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <el-dialog
      :title="dialog.title"
      v-model="dialog.visible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="800px"
      append-to-body
    >
      <el-form ref="designChangeFormRef" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="申请单编号" prop="formNo">
              <el-input v-model="form.formNo" placeholder="请输入申请单编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工程名称" prop="projectName"> <el-input v-model="form.projectName" placeholder="请输入工程名称" /> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="提出单位" prop="submitUnit">
              <el-input v-model="form.submitUnit" placeholder="请输入提出单位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专业" prop="specialty">
              <el-input v-model="form.specialty" placeholder="请输入专业" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="提出日期" prop="submitDate">
              <el-date-picker clearable v-model="form.submitDate" type="date"   value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择提出日期">
              </el-date-picker> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="卷册名称" prop="volumeName"> <el-input v-model="form.volumeName" placeholder="请输入卷册名称" /> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="卷册号" prop="volumeNo"> <el-input v-model="form.volumeNo" placeholder="请输入卷册号" /> </el-form-item
          ></el-col>
          <el-col :span="24">
            <el-form-item label="附图" prop="attachmentPic"> <image-upload v-model="form.attachmentPic" :fileSize="100" /> </el-form-item
          ></el-col>
          <el-col :span="24">
            <el-form-item label="变更原因" prop="changeReason">
              <el-checkbox-group v-model="form.changeReason">
                <el-checkbox v-for="dict in design_change_reason_type" :key="dict.value" :label="dict.value">
                  {{ dict.label }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item></el-col
          >
          <el-col :span="24">
            <el-form-item label="变更内容" prop="changeContent">
              <el-input v-model="form.changeContent" type="textarea" placeholder="请输入内容" /> </el-form-item
          ></el-col>
          <!-- <el-col :span="12">
            <el-form-item label="变更费用估算" prop="costEstimation">
              <el-input v-model="form.costEstimation" type="textarea" placeholder="请输入内容" /> </el-form-item
          ></el-col> -->
          <el-col :span="24">
            <el-form-item label="变更费用估算表" label-width="110px" prop="costEstimationFile">
              <file-upload v-model="form.costEstimationFile" :fileSize="100" /> </el-form-item
          ></el-col>
          <el-col :span="24">
            <el-form-item label="变更文件" prop="fileId"> <file-upload v-model="form.fileId" :fileSize="100" /> </el-form-item
          ></el-col>
          <el-col :span="24"
            ><el-form-item label="备注" prop="remark"> <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" /> </el-form-item
          ></el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <wordDetial ref="wordDetialRef"></wordDetial>
  </div>
</template>

<script setup name="DesignChange" lang="ts">
import { listDesignChange, getDesignChange, delDesignChange, addDesignChange, updateDesignChange } from '@/api/design/designChange';
import { DesignChangeVO, DesignChangeQuery, DesignChangeForm } from '@/api/design/designChange/types';
import { useUserStoreHook } from '@/store/modules/user';
import wordDetial from '@/components/wordDetial/index';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { design_change_reason_type } = toRefs<any>(proxy?.useDict('design_change_reason_type'));
// 获取用户 store
const userStore = useUserStoreHook();
// 从 store 中获取项目列表和当前选中的项目
const currentProject = computed(() => userStore.selectedProject);
const designChangeList = ref<DesignChangeVO[]>([]);
const buttonLoading = ref(false);
const wordDetialRef = ref<InstanceType<typeof wordDetial>>();
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const designChangeFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: DesignChangeForm = {
  id: undefined,
  projectId: currentProject.value?.id,
  formNo: undefined,
  projectName: undefined,
  submitUnit: undefined,
  specialty: undefined,
  submitDate: undefined,
  volumeName: undefined,
  volumeNo: undefined,
  attachmentPic: undefined,
  changeReason: [],
  changeContent: undefined,
  costEstimation: undefined,
  costEstimationFile: undefined,
  fileId: undefined,
  status: undefined,
  remark: undefined
};
const data = reactive<PageData<DesignChangeForm, DesignChangeQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectId: currentProject.value?.id,
    formNo: undefined,
    projectName: undefined,
    submitUnit: undefined,
    specialty: undefined,
    submitDate: undefined,
    volumeName: undefined,
    volumeNo: undefined,
    changeReason: undefined,
    status: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '主键id不能为空', trigger: 'blur' }],
    projectId: [{ required: true, message: '项目id不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询设计变更管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listDesignChange(queryParams.value);
  designChangeList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  designChangeFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: DesignChangeVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加设计变更';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: DesignChangeVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getDesignChange(_id);
  Object.assign(form.value, res.data);
  form.value.changeReason = form.value.changeReason.split(',');
  dialog.visible = true;
  dialog.title = '修改设计变更';
};

/** 提交按钮 */
const submitForm = () => {
  designChangeFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      form.value.changeReason = form.value.changeReason.join(',');
      if (form.value.id) {
        await updateDesignChange({ ...form.value }).finally(() => (buttonLoading.value = false));
      } else {
        await addDesignChange(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: DesignChangeVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除设计变更管理编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delDesignChange(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};
const handleView = (row) => {
  // 查看详情
  wordDetialRef.value?.openDialog(row,design_change_reason_type.value);
};
// 预览
const onOpen = (path: string) => {
    window.open(path, '_blank');
};
onMounted(() => {
  getList();
});
</script>
