<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="100px">
            <el-form-item label="协议单号" prop="contractSupplyNo">
              <el-input v-model="queryParams.contractSupplyNo" placeholder="请输入协议单号" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="供应商名称" prop="supplierName">
              <el-input v-model="queryParams.supplierName" placeholder="供应商名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker clearable
                v-model="queryParams.startTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择开始时间"
              />
            </el-form-item>
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker clearable
                v-model="queryParams.endTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择结束时间"
              />
            </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-button type="primary" icon="Plus" @click="handleAdd" v-hasPermi="['supplier:contractsupply:add']">新增</el-button>
            </el-form-item>
           
              
            
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          协议供货信息列表
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="contractsupplyList">
        <el-table-column label="主键ID" align="center" prop="id" v-if="false" />
        <el-table-column label="协议单号" align="center" prop="contractSupplyNo" />
        <el-table-column label="供应商编号" align="center" prop="supplyNo" />
        <el-table-column label="供应商名称" align="left" prop="supplierName" min-width="220" />
        <el-table-column label="商品数量" align="center" prop="productNumber" />
        <el-table-column label="开始时间" align="center" prop="startTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束时间" align="center" prop="endTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="剩余时限（天）" align="center" prop="timeRemaining" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="contract_supplier_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" @click="handleAudit(scope.row)" v-hasPermi="['supplier:contractsupply:edit']">审核</el-button>
            <el-divider direction="vertical" />
            <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['supplier:contractsupply:edit']">编辑</el-button>
          </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" width="500px" append-to-body>
      <el-form ref="contractsupplyFormRef" :model="form" :rules="rules" label-width="80px">
      </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>

    <!-- 审核对话框 -->
    <el-dialog title="审核" v-model="auditDialog.visible" width="500px" append-to-body>
      <el-form ref="auditFormRef" :model="auditForm" :rules="auditRules" label-width="100px">
        <el-form-item label="审核结果" prop="status">
          <el-select v-model="auditForm.status" placeholder="请选择" style="width: 100%;">
            <el-option label="生效" :value="1" />
            <el-option label="驳回" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAudit">确 定</el-button>
          <el-button @click="cancelAudit">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Contractsupply" lang="ts">
import { listContractsupply, getContractsupply, delContractsupply, addContractsupply, updateContractsupply, auditContractsupply } from '@/api/supplier/contractsupply';
import { ContractsupplyVO, ContractsupplyQuery, ContractsupplyForm } from '@/api/supplier/contractsupply/types';
import { useRouter } from 'vue-router';

const router = useRouter();

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { contract_supplier_status } = toRefs<any>(proxy?.useDict('contract_supplier_status'));

const contractsupplyList = ref<ContractsupplyVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const contractsupplyFormRef = ref<ElFormInstance>();
const auditFormRef = ref<ElFormInstance>();

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

const auditDialog = reactive({
  visible: false,
  currentRow: null as ContractsupplyVO | null
});

const auditForm = ref({
  status: undefined as number | undefined
});

const auditRules = {
  status: [
    { required: true, message: '请选择审核结果', trigger: 'change' }
  ]
};

const initFormData: ContractsupplyForm = {
}
const data = reactive<PageData<ContractsupplyForm, ContractsupplyQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    contractSupplyNo: undefined,
    supplierName: undefined,
    startTime: undefined,
    endTime: undefined,
    params: {
    }
  },
  rules: {
  }
});

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

/** 查询协议供货列表 */
const getList = async () => {
  loading.value = true;
  const res = await listContractsupply(queryParams.value);
  contractsupplyList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

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

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

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

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

/** 新增按钮操作 */
const handleAdd = () => {
  router.push('/supplier/contractsupply/add');
}

/** 修改按钮操作 */
const handleUpdate = async (row?: ContractsupplyVO) => {
  const _id = row?.id;
  if (!_id) {
    proxy?.$modal.msgWarning('请选择要编辑的数据');
    return;
  }
  router.push(`/supplier/contractsupply/edit/${_id}`);
}

/** 审核按钮操作 */
const handleAudit = (row: ContractsupplyVO) => {
  auditDialog.currentRow = row;
  auditForm.value.status = undefined;
  auditDialog.visible = true;
};

/** 提交审核 */
const submitAudit = () => {
  auditFormRef.value?.validate(async (valid: boolean) => {
    if (valid && auditDialog.currentRow) {
      try {
        await auditContractsupply({
          id: auditDialog.currentRow.id!,
          status: auditForm.value.status!
        });
        proxy?.$modal.msgSuccess("审核成功");
        auditDialog.visible = false;
        await getList();
      } catch (e) {
        console.error('审核失败:', e);
      }
    }
  });
};

/** 取消审核 */
const cancelAudit = () => {
  auditDialog.visible = false;
  auditForm.value.status = undefined;
};

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

/** 删除按钮操作 */
const handleDelete = async (row?: ContractsupplyVO) => {
  const _ids = row?.id;
  if (!_ids) {
    proxy?.$modal.msgWarning('请选择要删除的数据');
    return;
  }
  await proxy?.$modal.confirm('是否确认删除协议供货编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delContractsupply(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('supplier/contractsupply/export', {
    ...queryParams.value
  }, `contractsupply_${new Date().getTime()}.xlsx`)
}

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

<style scoped>

</style>
