<template>
  <div class="p-2">
    <el-card shadow="never">
      <el-table v-loading="loading" :data="salesStatusApplicationVO">
        <el-table-column label="产品编码" align="center" prop="productCode" />
        <el-table-column label="产品名称" align="center" prop="productName" />
        <!--        <el-table-column label="产品状态变化" align="center" prop="changeContent" />-->
        <el-table-column label="产品起售日期" align="center" prop="salesStartDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.salesStartDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="产品停售日期" align="center" prop="salesEndDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.salesEndDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="产品销售限额(万元)" align="center" prop="salesLimit" />
        <el-table-column label="申请时间" align="center" prop="applicationTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.applicationTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="申请人" align="center" prop="applicant" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="查看详情" placement="top">
              <el-button v-hasPermi="['product:audit:query']" link type="primary" icon="View" @click="viewDetails(scope.row)">查看详情</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" v-model:page="pageQuery.pageNum" v-model:limit="pageQuery.pageSize" :total="total" @pagination="getList" />
    </el-card>

    <!-- 查看详情页面-->
    <el-dialog v-model="viewDetailsDialog" :title="产品起停售申请" width="80%" append-to-body>
      <el-form ref="queryFormRef" v-loading="detailsLoading" :model="prodSalesStatusApplicationVo" :rules="detailsRules">
        <el-row>
          <el-form-item label="产品编号" prop="productCode" label-width="130px">
            <el-select v-model="prodSalesStatusApplicationVo.productCode" placeholder="产品编号" style="width: 220px" clearable filterable />
          </el-form-item>
          <el-form-item label="产品状态" label-width="130px" prop="salesStatus">
            <el-select v-model="prodSalesStatusApplicationVo.salesStatus" placeholder="产品状态" style="width: 220px" clearable>
              <el-option v-for="dict in sales_status" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="产品销售限额(万元)" label-width="130px" prop="salesLimit">
            <el-input-number v-model="prodSalesStatusApplicationVo.salesLimit" clearable />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="产品起售日期" prop="salesStartDate" label-width="130px">
            <el-date-picker
              v-model="prodSalesStatusApplicationVo.salesStartDate"
              clearable
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择产品起售日期"
            />
          </el-form-item>
          <el-form-item label="产品停售日期" label-width="130px" prop="salesEndDate">
            <el-date-picker
              v-model="prodSalesStatusApplicationVo.salesEndDate"
              clearable
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择产品停售日期"
            />
          </el-form-item>
          <el-form-item label="承保截止时间" prop="signEndDate" label-width="130px">
            <el-date-picker
              v-model="prodSalesStatusApplicationVo.signEndDate"
              :disabled="prodSalesStatusApplicationVo.salesStatus != '1'"
              clearable
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择承保截止时间"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item style="width: 100%">
            <el-table :data="prodSalesStatusApplicationVo.channelApplicationList">
              <el-table-column label="销售渠道" style="width: 20%" align="center" prop="salesChannel">
                <template #default="scope">
                  <dict-tag :options="sales_channel" :value="scope.row.salesChannel" />
                </template>
              </el-table-column>
              <el-table-column label="销售起期" style="width: 20%" align="center" prop="salesStartDate">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.salesStartDate, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="销售止期" style="width: 20%" align="center" prop="salesEndDate">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.salesEndDate, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="销售限额(万元)" style="width: 20%" align="center" prop="salesLimit" />
              <el-table-column label="承保截止时间" align="center" prop="signEndDate">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.signEndDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item style="width: 100%" prop="channels">
            <el-table :data="prodSalesStatusApplicationVo.institutionApplicationList">
              <el-table-column label="销售渠道" style="width: 20%" align="center" prop="salesChannel">
                <template #default="scope">
                  <dict-tag :options="sales_channel" :value="scope.row.salesChannel" />
                </template>
              </el-table-column>
              <el-table-column label="销售机构" style="width: 25%" align="center" prop="salesInstitution">
                <template #default="scope">
                  <dict-tag :options="sys_managecom" :value="scope.row.salesInstitution" />
                </template>
              </el-table-column>
              <el-table-column label="销售起期" style="width: 25%" align="center" prop="salesStartDate">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.salesStartDate, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="销售止期" align="center" prop="salesEndDate">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.salesEndDate, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="销售限额(万元)" align="center" prop="salesLimit" />
              <el-table-column label="承保截止时间" align="center" prop="signEndDate">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.signEndDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item v-if="prodSalesStatusApplicationVo.salesStatus === '1'" label="产品停售原因:" prop="stopSalesReason">
            <el-input
              v-model="prodSalesStatusApplicationVo.stopSalesReason"
              style="width: 260px; line-height: 100px"
              :autosize="{ minRows: 2, maxRows: 7 }"
              type="textarea"
              placeholder="产品停售原因"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item>
            <el-button v-hasPermi="['product:audit:pass']" type="primary" icon="Check" @click="Approved">审批通过</el-button>
          </el-form-item>
          <el-form-item>
            <el-button v-hasPermi="['product:audit:reject']" type="warning" icon="RefreshLeft" style="margin-left: 20px" @click="returnApplication"
              >退回申请
            </el-button>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="审批退回原因:" prop="auditOpinion">
            <el-input
              v-model="prodSalesStatusAuditBo.auditOpinion"
              style="width: 260px; line-height: 100px"
              :autosize="{ minRows: 2, maxRows: 7 }"
              type="textarea"
              placeholder="审批退回原因"
            />
          </el-form-item>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup name="SalesStatusApplication" lang="ts">
import { queryApplicationList, infoByApplicationId, auditPass, rejectApplication } from '@/api/product/audit';
import { getInfo } from '@/api/login';
import {
  SalesStatusApplicationVO,
  SalesStatusApplicationQuery,
  SalesStatusApplicationForm,
  ProdSalesStatusApplicationVo,
  ProdSalesStatusAuditBo
} from '@/api/product/audit/types';
import { FormRules } from 'element-plus';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

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 salesStatusApplicationFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const detailsLoading = ref(false);
const initFormData: SalesStatusApplicationForm = {
  applicationId: undefined,
  productCode: undefined,
  productName: undefined,
  system: undefined,
  salesStatus: undefined,
  salesStartDate: undefined,
  salesEndDate: undefined,
  salesLimit: undefined,
  changeContent: undefined,
  applicationStatus: undefined,
  applicant: undefined,
  applicationTime: undefined
};
//字典转换
const { email_notice, sales_status, sales_intitution, sales_channel, system, prod_application_status, sys_managecom } = toRefs<any>(
  proxy?.useDict('email_notice', 'sales_status', 'sales_intitution', 'sales_channel', 'system', 'prod_application_status', 'sys_managecom')
);
const data = reactive<PageData<SalesStatusApplicationForm, SalesStatusApplicationQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    productCode: undefined,
    productName: undefined,
    system: undefined,
    salesStatus: undefined,
    salesStartDate: undefined,
    salesEndDate: undefined,
    salesLimit: undefined,
    changeContent: undefined,
    applicationStatus: undefined,
    applicant: undefined,
    applicationTime: undefined,
    params: {}
  },
  rules: {
    applicationId: [{ required: true, message: '申请编码不能为空', trigger: 'blur' }],
    productCode: [{ required: true, message: '产品编码不能为空', trigger: 'blur' }],
    productName: [{ required: true, message: '产品名称不能为空', trigger: 'blur' }],
    system: [{ required: true, message: '归属系统不能为空', trigger: 'blur' }],
    salesStatus: [{ required: true, message: '产品销售状态不能为空', trigger: 'change' }],
    salesStartDate: [{ required: true, message: '产品销售起期不能为空', trigger: 'blur' }],
    salesEndDate: [{ required: true, message: '产品销售止期不能为空', trigger: 'blur' }],
    salesLimit: [{ required: true, message: '产品销售限额不能为空', trigger: 'blur' }],
    changeContent: [{ required: true, message: '变更内容不能为空', trigger: 'blur' }],
    applicationStatus: [{ required: true, message: '申请状态不能为空', trigger: 'change' }],
    applicant: [{ required: true, message: '申请人不能为空', trigger: 'blur' }],
    applicationTime: [{ required: true, message: '申请时间不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);
const viewDetailsDialog = ref(false);
const pageQuery = ref({
  pageNum: 1,
  pageSize: 10
});
const salesStatusApplicationVO = ref<SalesStatusApplicationVO>();
const prodSalesStatusApplicationVo = ref<ProdSalesStatusApplicationVo>({
  applicationId: undefined,
  productCode: undefined,
  productName: undefined,
  system: undefined,
  salesStatus: undefined,
  salesStartDate: undefined,
  salesEndDate: undefined,
  salesLimit: undefined,
  changeContent: undefined,
  applicationStatus: undefined,
  applicant: undefined,
  applicationTime: undefined,
  emailNotice: undefined,
  stopSalesReason: undefined,
  signEndDate: undefined,
  channelApplicationList: [],
  institutionApplicationList: []
});
const prodSalesStatusAuditBo = ref<ProdSalesStatusAuditBo>({
  applicationId: undefined,
  auditOpinion: undefined,
  auditor: undefined
});
/** 查询产品销售状态申请列表 */
const getList = async () => {
  loading.value = true;
  await queryApplicationList(pageQuery.value)
    .then((res) => {
      salesStatusApplicationVO.value = res.rows;
      total.value = res.total;
      loading.value = false;
    })
    .catch((err) => {
    });
};

/** 根据申请id查询申请详情（状态申请、渠道申请、机构申请）*/
const viewDetails = async (row: prodSalesStatusApplicationVo) => {
  viewDetailsDialog.value = true;
  detailsLoading.value = true;
  infoByApplicationId(row.applicationId)
    .then((res) => {
      prodSalesStatusApplicationVo.value = res.data;
      detailsLoading.value = false;
    })
    .catch((err) => {
    });
};

/** 审核通过*/
const Approved = async () => {
  try {
    // 设置申请ID
    prodSalesStatusAuditBo.value.applicationId = prodSalesStatusApplicationVo.value.applicationId;

    // 提交审核
    await auditPass(prodSalesStatusAuditBo.value);

    // 操作成功后处理
    viewDetailsDialog.value = false;
    await getList(); // 刷新列表
    prodSalesStatusAuditBo.value.auditOpinion = ''; // 清空意见
  } catch (err) {
  }
};
/** 退回申请*/
const returnApplication = async () => {
  try {
    // 获取审批退回原因
    const auditOpinion = prodSalesStatusAuditBo.value.auditOpinion;

    // 验证逻辑
    if (!auditOpinion || auditOpinion.trim() === '') {
      proxy?.$modal.msgError('审批退回原因不能为空');
      return; // 阻断提交
    }

    if (auditOpinion.length > 100) {
      proxy?.$modal.msgError('审批退回原因不能超过100个字符');
      return; // 阻断提交
    }

    // 设置申请ID
    prodSalesStatusAuditBo.value.applicationId = prodSalesStatusApplicationVo.value.applicationId;

    // 提交退回申请
    await rejectApplication(prodSalesStatusAuditBo.value);

    // 处理成功结果
    viewDetailsDialog.value = false;
    await getList(); // 刷新列表
    prodSalesStatusAuditBo.value.auditOpinion = ''; // 清空原因

    proxy?.$modal.msgSuccess('退回申请成功');
  } catch (err) {
    proxy?.$modal.msgError('退回申请失败，请重试');
  }
};

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