<template>
    <div class="p-2">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
            <div class="search" v-show="showSearch">
                <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
                    <el-form-item label="企业名称" prop="keywords">
                        <el-input
                            v-model="queryParams.keywords"
                            placeholder="请输入企业名称"
                            clearable
                            style="width: 240px"
                            @keyup.enter="handleQuery"
                        />
                    </el-form-item>
                    <!-- <el-form-item label="审核时间" prop="approveTime">
            <el-date-picker clearable v-model="queryParams.approveTime" type="date" value-format="YYYY-MM-DD"
              placeholder="请选择审核时间" />
          </el-form-item> -->
                    <el-form-item label="审核状态" prop="applyStatus">
                        <el-select v-model="queryParams.applyStatus" style="width: 100%;" placeholder="请选择审核状态" clearable>
                            <el-option v-for="dict in cpy_res_status" :key="dict.value" :label="dict.label" :value="dict.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="申请类别" prop="applyType">
                        <el-select v-model="queryParams.applyType" style="width: 100%;" placeholder="请选择申请类别" clearable>
                            <el-option v-for="dict in apply_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                        </el-select>
                    </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>
            </div>
        </transition>

        <el-card shadow="never">
            <el-table v-loading="loading" :data="geoIdentityApplyList" border @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="企业名称" align="center" prop="cpyName" show-overflow-tooltip width="150px" />
                <el-table-column label="统一社会信用代码" align="center" prop="creditCode" show-overflow-tooltip width="150px" />
                <!-- <el-table-column label="营业执照" align="center" prop="bizLicence" width="150px">
          <template #default="scope">
            {{ scope.row.bizLicence ? scope.row.bizLicence.fileName : '-' }}
          </template>
</el-table-column>
<el-table-column label="法人代表身份证" align="center" prop="leageRpstIdCard" width="120px" show-overflow-tooltip>
  <template #default="scope">
            {{ scope.row.leageRpstIdCard ? scope.row.leageRpstIdCard.fileName : '-' }}
          </template>
</el-table-column>
<el-table-column label="合同" align="center" prop="contract" width="100px" show-overflow-tooltip>
  <template #default="scope">
            {{ scope.row.contract ? scope.row.contract.fileName : '-' }}
          </template>
</el-table-column>
<el-table-column label="样品图片" align="center" prop="samplePic" width="100px" show-overflow-tooltip>
  <template #default="scope">
            <image-preview :src="scope.row.samplePic" width="50" height="50" />
          </template>
</el-table-column>
<el-table-column label="产品图片" align="center" prop="productPic" width="100px">
  <template #default="scope">
            <image-preview :src="scope.row.productPic" width="50" height="50" />
          </template>
</el-table-column>
<el-table-column label="生产许可证" align="center" prop="produceLicense" width="100px" show-overflow-tooltip>
  <template #default="scope">
            {{ scope.row.produceLicense ? scope.row.produceLicense.fileName : '-' }}
          </template>
</el-table-column>
<el-table-column label="商标申请书" align="center" prop="bizApply" width="100px" show-overflow-tooltip>
  <template #default="scope">
            {{ scope.row.bizApply ? scope.row.bizApply.fileName : '-' }}
          </template>
</el-table-column>
<el-table-column label="续签申请书" align="center" prop="renewalApply" width="100px" show-overflow-tooltip>
  <template #default="scope">
            {{ scope.row.renewalApply ? scope.row.renewalApply.fileName : '-' }}
          </template>
</el-table-column>
<el-table-column label="注销申请书" align="center" prop="offApply" width="100px" show-overflow-tooltip>
  <template #default="scope">
            {{ scope.row.offApply ? scope.row.offApply.fileName : '-' }}
          </template>
</el-table-column> -->
                <el-table-column label="申请类别" align="center" prop="applyType">
                    <template #default="{ row }">
                        {{ selectDictLabel(apply_type, row.applyType) || '-' }}
                    </template>
                </el-table-column>
                <el-table-column label=" 主体类别" align="center" prop="bizType" show-overflow-tooltip min-width="150px">
                    <template #default="{ row }">
                        <span v-for="(item, index) in row.bizType" :key="index">
                            {{ selectDictLabel(biz_type, item) }}<span v-if="index < row.bizType.length - 1">, </span>
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="提交时间" align="center" prop="createTime" width="180">
                    <template #default="scope">
                        <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="审核状态" align="center">
                    <template #default="{ row }">
                        {{ selectDictLabel(cpy_res_status, row.applyStatus) || '-' }}
                    </template>
                </el-table-column>
                <el-table-column label="审核时间" align="center" prop="approveTime" width="180">
                    <template #default="scope">
                        <span>{{ parseTime(scope.row.approveTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="审核人" align="center" prop="approveByName" />
                <el-table-column label="审核备注" align="center" prop="approveRemark" show-overflow-tooltip />
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="350">
                    <template #default="scope">
                        <el-button @click="handleUpdate(scope.row)" type="success">详情</el-button>
                        <template v-if="scope.row.applyStatus == '0'">
                            <el-button @click="handleApproval(scope.row, '1')" type="success">审核通过</el-button>
                            <el-button @click="handleApproval(scope.row, '2')" type="warning">审核不通过</el-button>
                        </template>
                    </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 :close-on-click-modal="false" :title="dialog.title" v-model="dialog.visible" width="850px" append-to-body>
            <el-form ref="geoIdentityApplyFormRef" :model="form" label-position="top" :rules="rules" label-width="110px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="主体类型" prop="bizType">
                            {{ selectDictLabels(biz_type, form.bizType, ',') }}
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="经营组织简介" prop="orgSummary">
                    <el-input v-model="form.orgSummary" type="textarea" placeholder="请输入内容" disabled />
                </el-form-item>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="“昭通天麻”地理标志证明商标使用申请书" prop="bizApply">
                            <el-link type="primary" @click="urlOpen(form.bizApply?.url)" :underline="false">
                                {{ form.bizApply?.fileName }}
                            </el-link>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="营业执照" prop="bizLicence">
                            <el-link type="primary" @click="urlOpen(form.bizLicence?.url)" :underline="false">
                                {{ form.bizLicence?.fileName }}
                            </el-link>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="法人代表身份证" prop="leageRpstIdCard">
                            <el-link type="primary" @click="urlOpen(form.leageRpstIdCard?.url)" :underline="false">
                                {{ form.leageRpstIdCard?.fileName }}
                            </el-link>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="“昭通天麻”地理标志证明商标许可使用合同" prop="contract">
                            <el-link type="primary" @click="urlOpen(form.contract?.url)" :underline="false">
                                {{ form.contract?.fileName }}
                            </el-link>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="具有法定检测机构三个月内出具的检测证书及送检样品照片" prop="samplePic">
                            <el-link type="primary" @click="urlOpen(form.samplePic?.url)" :underline="false">
                                {{ form.samplePic?.fileName }}
                            </el-link>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="生产许可证或经营许可证" prop="produceLicense">
                            <el-link type="primary" @click="urlOpen(form.produceLicense?.url)" :underline="false">
                                {{ form.produceLicense?.fileName }}
                            </el-link>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="产品包装设计图" prop="productPic">
                          <el-image
                                style="width: 150px; height: 150px"
                                :src="form.productPic"
                                :preview-src-list="picSplit(form.productPic)"
                            ></el-image>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12" v-if="form.renewalApply">
                        <el-form-item label="续签申请书" prop="renewalApply">
                            <el-link type="primary" @click="urlOpen(form.renewalApply?.url)" :underline="false">
                                {{ form.renewalApply?.fileName }}
                            </el-link>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" v-if="form.offApply">
                        <el-form-item label="注销申请书" prop="offApply">
                            <el-link type="primary" @click="urlOpen(form.offApply?.url)" :underline="false">
                                {{ form.offApply?.fileName }}
                            </el-link>
                        </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>
    </div>
</template>

<script setup name="GeoIdentityApply" lang="ts">
import {
    listGeoIdentityApply,
    getGeoIdentityApply,
    delGeoIdentityApply,
    addGeoIdentityApply,
    updateGeoIdentityApply,
    geoApproval
} from '@/api/smarttrace/geoIdentityApply';
import { GeoIdentityApplyVO, GeoIdentityApplyQuery, GeoIdentityApplyForm } from '@/api/smarttrace/geoIdentityApply/types';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
import { CircleCheck, CircleClose } from '@element-plus/icons-vue';
import { split } from 'postcss/lib/list';
const geoIdentityApplyList = ref<GeoIdentityApplyVO[]>([]);
const { cpy_res_status, apply_type, biz_type } = toRefs<any>(proxy?.useDict('cpy_res_status', 'apply_type', 'biz_type'));
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 geoIdentityApplyFormRef = ref<ElFormInstance>();

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

const initFormData: GeoIdentityApplyForm = {
    id: undefined,
    orgSummary: undefined,
    brandLogoApply: undefined,
    bizLicence: undefined,
    leageRpstIdCard: undefined,
    contract: undefined,
    samplePic: undefined,
    productPic: undefined,
    produceLicense: undefined,
    bizApply: undefined,
    renewalApply: undefined,
    offApply: undefined,
    bizType: undefined,
    applyType: undefined,
    applyStatus: undefined,
    approveTime: undefined,
    approveBy: undefined,
    approveRemark: undefined,
    cpyid: undefined,
    partnerId: undefined
};
const data = reactive<PageData<GeoIdentityApplyForm, GeoIdentityApplyQuery>>({
    form: { ...initFormData },
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        orgSummary: undefined,
        brandLogoApply: undefined,
        bizLicence: undefined,
        leageRpstIdCard: undefined,
        contract: undefined,
        samplePic: undefined,
        productPic: undefined,
        produceLicense: undefined,
        bizApply: undefined,
        renewalApply: undefined,
        offApply: undefined,
        bizType: undefined,
        applyType: undefined,
        applyStatus: '0',
        approveTime: undefined,
        approveBy: undefined,
        approveRemark: undefined,
        cpyid: undefined,
        partnerId: undefined,
        params: {}
    },
    rules: {
        id: [{ required: true, message: 'ID不能为空', trigger: 'blur' }],
        orgSummary: [{ required: true, message: '经营组织简介不能为空', trigger: 'blur' }],
        bizLicence: [{ required: true, message: '营业执照不能为空', trigger: 'blur' }],
        leageRpstIdCard: [{ required: true, message: '法人代表身份证不能为空', trigger: 'blur' }],
        contract: [{ required: true, message: '合同不能为空', trigger: 'blur' }],
        samplePic: [{ required: true, message: '样品图片不能为空', trigger: 'blur' }],
        productPic: [{ required: true, message: '产品图片不能为空', trigger: 'blur' }],
        produceLicense: [{ required: true, message: '生产许可证不能为空', trigger: 'blur' }],
        bizApply: [{ required: true, message: '商标申请书不能为空', trigger: 'blur' }],
        renewalApply: [{ required: true, message: '续签申请书不能为空', trigger: 'blur' }],
        offApply: [{ required: true, message: '注销申请书不能为空', trigger: 'blur' }],
        bizType: [{ required: true, message: '业务类别不能为空', trigger: 'change' }],
        applyType: [{ required: true, message: '申请类别不能为空', trigger: 'change' }],
        applyStatus: [{ required: true, message: '申请状态不能为空', trigger: 'change' }],
        approveTime: [{ required: true, message: '审核时间不能为空', trigger: 'blur' }],
        approveBy: [{ required: true, message: '审核人不能为空', trigger: 'blur' }],
        approveRemark: [{ required: true, message: '审核备注不能为空', trigger: 'blur' }],
        cpyid: [{ required: true, message: '企业ID不能为空', trigger: 'blur' }],
        partnerId: [{ required: true, message: '合作伙伴ID不能为空', trigger: 'blur' }]
    }
});

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

const picSplit = (pic: string) => {
    console.log(pic);
    return pic.split(',');
};

/** 查询地址标志申报列表 */
const getList = async () => {
    loading.value = true;
    const res = await listGeoIdentityApply(queryParams.value);
    geoIdentityApplyList.value = res.rows;
    total.value = res.total;
    loading.value = false;
};

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

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

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

/**
 *
 * @param url 打开窗口
 */
const urlOpen = (url: string) => {
    window.open(url);
};

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

/**
 * 申请审批
 */
const handleApproval = async (row: any, res: string) => {
    if (res === '1') {
        ElMessageBox.confirm('确认审核通过?', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'success',
            icon: markRaw(CircleCheck)
        })
            .then(() => {
                const params = {
                    approvalType: '2',
                    targetId: row.id,
                    res
                };
                approvalAjax(params);
            })
            .catch(() => {
                proxy?.$modal.msgWarning('取消审核');
            });
    } else {
        ElMessageBox.prompt('确认审核不通过', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            inputPlaceholder: '不通过理由',
            inputErrorMessage: '请填写不通过理由',
            type: 'error',
            icon: markRaw(CircleClose),
            inputValidator: (value) => {
                return value ? true : false;
            }
        })
            .then(({ value }) => {
                const params = {
                    approvalType: '2',
                    targetId: row.id,
                    res,
                    msg: value
                };
                approvalAjax(params);
            })
            .catch(() => {
                proxy?.$modal.msgWarning('取消审核');
            });
    }
};
const approvalAjax = async (params: any) => {
    proxy?.$modal.loading('审核中...');
    const res = await geoApproval(params).catch(() => {});
    proxy?.$modal.closeLoading();
    if (!res) return;
    proxy?.$modal.msgSuccess('操作完成');
    getList();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: GeoIdentityApplyVO[]) => {
    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?: GeoIdentityApplyVO) => {
    reset();
    const _id = row?.id || ids.value[0];
    const res = await getGeoIdentityApply(_id);
    Object.assign(form.value, res.data);
    dialog.visible = true;
    dialog.title = '修改地址标志申报';
};

/** 提交按钮 */
const submitForm = () => {
    geoIdentityApplyFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
            buttonLoading.value = true;
            if (form.value.id) {
                await updateGeoIdentityApply(form.value).finally(() => (buttonLoading.value = false));
            } else {
                await addGeoIdentityApply(form.value).finally(() => (buttonLoading.value = false));
            }
            proxy?.$modal.msgSuccess('修改成功');
            dialog.visible = false;
            await getList();
        }
    });
};

/** 删除按钮操作 */
const handleDelete = async (row?: GeoIdentityApplyVO) => {
    const _ids = row?.id || ids.value;
    await proxy?.$modal.confirm('是否确认删除地址标志申报编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
    await delGeoIdentityApply(_ids);
    proxy?.$modal.msgSuccess('删除成功');
    await getList();
};

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

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