<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" :inline="true" :model="queryParams" label-width="100">
            <el-form-item label="项目编号：" prop="productSn">
              <el-input v-model="queryParams.productSn" clearable placeholder="请输入项目编号"
                        @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="项目名称：" prop="productName">
              <el-input v-model="queryParams.productName" clearable placeholder="请输入项目名称"
                        @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="项目类型：" prop="productType">
              <el-select v-model="queryParams.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-form-item>
              <el-button icon="Search" type="primary" @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 v-hasPermi="['zjk:product:add']" icon="Plus" plain type="primary"
                       @click="handleAdd">新增
            </el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['zjk:product:edit']">修改</el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button :disabled="multiple" icon="Delete" plain type="danger" @click="handleDelete()"
            >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['zjk:product:export']" icon="Download" plain type="warning"
                       @click="handleExport">导出
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="projectList" @selection-change="handleSelectionChange">
        <el-table-column :selectable="(row)=>row.isItem == '0'" align="center" type="selection" width="55" />
        <el-table-column align="center" label="项目编号" prop="productSn" />
        <el-table-column align="center" label="项目名称" prop="productName">
          <template #default="scope">
            <span style="color: #36d;cursor: pointer;" @click="jumpToDetail(scope.row)">{{ scope.row.productName
              }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="项目单位" prop="productUnit" />
        <el-table-column align="center" label="联系人" prop="unitBy" />
        <el-table-column align="center" label="联系电话" prop="unitConcat" />
        <el-table-column align="center" label="项目类型" prop="productType">
          <template #default="scope">
            <dict-tag :options="project_type" :value="scope.row.productType"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="审核状态" prop="approvalStatus">
          <template #default="scope">
            {{ examineStatusOptions[+scope.row.approvalStatus || 0] }}
          </template>
        </el-table-column>

        <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
          <template #default="scope">
            <span v-if="roles.includes('jg')" :style="scope.row.approvalStatus == '0'?'color: #36d;cursor: pointer;':'color:gray;'"
                  @click="handleExamine(scope.row)"
            >审核</span>
            <el-divider v-if="roles.includes('jg')" direction="vertical" />
            <span :style="scope.row.approvalStatus == '2'?'color: #36d;cursor: pointer;':'color:gray;'"
                  @click="handleUpdate(scope.row)"
            >修改</span>
            <el-divider direction="vertical" />
            <span :style="scope.row.approvalStatus == '2'?'color: #36d;cursor: pointer;':'color:gray;'"
                  @click="handleDelete(scope.row)"
            >删除</span>
            <!-- </el-tooltip> -->
            <el-divider direction="vertical" />
            <span :style="scope.row.isItem == 0 ? 'color: #36d;cursor: pointer;' : 'color: gray;'"
                  @click="handleVerify(scope.row)"
            >校验</span>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum"
                  :total="total" @pagination="getList" />
    </el-card>
  </div>
</template>

<script lang="ts" name="Project" setup>
import { listProject, getProject, delProject, addProject, updateProject, verifyHmac } from '@/api/project/maintain';
import { ProjectVO, ProjectQuery, ProjectForm } from '@/api/project/maintain/types';
import useUserStore from '@/store/modules/user';
const userStore = useUserStore();

const roles = computed(() => userStore.roles);

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { project_type } = toRefs<any>(proxy?.useDict('project_type'));
const projectList = ref<ProjectVO[]>([]);
const buttonLoading = ref(false);
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 projectFormRef = ref<ElFormInstance>();

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

const examineStatusOptions = ['待审批', '已通过', '已驳回']

const initFormData: ProjectForm = {
  revision: undefined,
  productSn: undefined,
  productName: undefined,
  productType: undefined,
  productFund: undefined,
  productOpenplace: undefined,
  productOpentime: undefined,
  productConcatuser: undefined,
  productConcatphone: undefined,
  productUniformcode: undefined,
  productOwnername: undefined,
  productTransactmode: undefined,
  productTotalamount: undefined,
  createdBy: undefined,
  createdTime: undefined,
  id: undefined
};
const data = reactive<PageData<ProjectForm, ProjectQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    revision: undefined,
    productSn: undefined,
    productName: undefined,
    productType: undefined,
    productFund: undefined,
    productOpenplace: undefined,
    productOpentime: undefined,
    productConcatuser: undefined,
    productConcatphone: undefined,
    productUniformcode: undefined,
    productOwnername: undefined,
    productTransactmode: undefined,
    productTotalamount: undefined,
    createdBy: undefined,
    createdTime: undefined,
    params: {}
  },
  rules: {
    revision: [
      { required: true, message: '$comment不能为空', trigger: 'blur' }
    ],
    productSn: [
      { required: true, message: '$comment不能为空', trigger: 'blur' }
    ],
    productName: [
      { required: true, message: '$comment不能为空', trigger: 'blur' }
    ],
    productType: [
      { required: true, message: '$comment不能为空', trigger: 'change' }
    ],
    productFund: [
      { required: true, message: '$comment不能为空', trigger: 'blur' }
    ],
    productOpenplace: [
      { required: true, message: '$comment不能为空', trigger: 'blur' }
    ],
    productOpentime: [
      { required: true, message: '$comment不能为空', trigger: 'blur' }
    ],
    productConcatuser: [
      { required: true, message: '$comment不能为空', trigger: 'blur' }
    ],
    productConcatphone: [
      { required: true, message: '$comment不能为空', trigger: 'blur' }
    ],
    productUniformcode: [
      { required: true, message: '$comment不能为空', trigger: 'blur' }
    ],
    productOwnername: [
      { required: true, message: '$comment不能为空', trigger: 'blur' }
    ],
    productTransactmode: [
      { required: true, message: '$comment不能为空', trigger: 'blur' }
    ],
    productTotalamount: [
      { required: true, message: '$comment不能为空', trigger: 'blur' }
    ],
    createdBy: [
      { required: true, message: '$comment不能为空', trigger: 'blur' }
    ],
    createdTime: [
      { required: true, message: '$comment不能为空', trigger: 'blur' }
    ],
    id: [
      { required: true, message: '$comment不能为空', trigger: 'blur' }
    ]
  }
});

const router = useRouter();
const route = useRoute();
const { queryParams, form, rules } = toRefs(data);

/** 查询【请填写功能名称】列表 */
const getList = async () => {
  loading.value = true;
  const res = await listProject(queryParams.value);
  projectList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};


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

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

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

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

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

/** 查询详情 */
const jumpToDetail = async (row?: ProjectVO) => {
  router.push({ path: '/project/maintainDetail', query: { id: row.id || ids.value[0], mode: 'view', approvalStatus: row.approvalStatus } });
  // loading.value = true;
  // const res = await listProject(queryParams.value);
  // projectList.value = res.rows;
  // total.value = res.total;
  // loading.value = false;
};

/** 新增按钮操作 */
const handleAdd = () => {
  router.push({ path: '/project/maintainDetail', query: { mode: 'add' } });
  // reset();
  // dialog.visible = true;
  // dialog.title = "添加【请填写功能名称】";
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ProjectVO) => {
  if (row.isItem == 1) {
    return;
  }
  router.push({ path: '/project/maintainDetail', query: { id: row.id || ids.value[0], mode: 'edit' } });
  // reset();
  // const _revision = row?.revision || ids.value[0]
  // const res = await getProject(_revision);
  // Object.assign(form.value, res.data);
  // dialog.visible = true;
  // dialog.title = "修改【请填写功能名称】";
};
/** 审核按钮操作 */
const handleExamine = async (row?: ProjectVO) => {
  router.push({ path: '/project/maintainDetail', query: { id: row.id || ids.value[0], mode: 'examine' } });
  // reset();
  // const _revision = row?.revision || ids.value[0]
  // const res = await getProject(_revision);
  // Object.assign(form.value, res.data);
  // dialog.visible = true;
  // dialog.title = "修改【请填写功能名称】";
};

/** 提交按钮 */
const submitForm = () => {
  projectFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.revision) {
        await updateProject(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addProject(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: ProjectVO) => {
  if (row) {
    if (row.isItem == 1) {
      return;
    }
  }
  const idds = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除【请填写功能名称】编号为"' + idds + '"的数据项？').finally(() => loading.value = false);
  await delProject(idds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('/zjk-api/product/export', {
    ...queryParams.value
  }, `product_${new Date().getTime()}.xlsx`);
};

/**hmac校验*/
function handleVerify(row: any) {
  verifyHmac({
    bizType: 'product',
    id: row.id,
    fields: []
  })
    .then(result => {
      if (result.match) {
        ElMessage.success('校验通过');
      } else {
        ElMessage.error(`校验失败，该信息被篡改`);
      }
    })
    .catch(err => {
      ElMessage.error('接口请求失败: ' + (err.response?.data?.msg || err.message));
    });
}

onActivated(() => {
  getList();
});
onMounted(() => {
  getList();
});
</script>
