<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="108px">
                    <el-form-item label="合作伙伴名称" prop="partnerName">
                        <el-input v-model="queryParams.partnerName" placeholder="请输入合作伙伴名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
                    </el-form-item>
                    <el-form-item label="合作伙伴编码" prop="partnerCode">
                        <el-input v-model="queryParams.partnerCode" placeholder="请输入合作伙伴编码" clearable style="width: 240px" @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>
            </div>
        </transition>
        <el-tabs v-model="activeTab" style="padding: 5px;">
            <el-tab-pane label="合作伙伴" name="tab1">
                <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="['smarttrace:partner:add']">新增</el-button>
                            </el-col>
                            <el-col :span="1.5">
                                <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['smarttrace:partner:edit']">修改</el-button>
                            </el-col>
                            <el-col :span="1.5">
                                <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['smarttrace:partner:remove']">删除</el-button>
                            </el-col>
                            <el-col :span="1.5">
                                <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['smarttrace:partner:export']">导出</el-button>
                            </el-col>
                            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
                        </el-row>
                    </template>

                    <el-table v-loading="loading" :data="partnerList">
                        <el-table-column type="index" label="序号" width="55" align="center" />
                        <el-table-column label="合作伙伴名称" align="center" prop="partnerName" />
                        <el-table-column label="合作伙伴编码" align="center" prop="partnerCode" />
                        <el-table-column label="备注" align="center" prop="remark" />
                        <el-table-column label="已授权应用" align="center" prop="apps">
                            <template #default="scope">
                                <el-button type="text" @click="viewApps(scope.row)">查看({{ scope.row.appCount || 0 }})</el-button>
                            </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}') }}</span>
                            </template>
                        </el-table-column>
                        <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="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['smarttrace:partner:edit']"></el-button>
                                </el-tooltip>
                                <el-tooltip content="删除" placement="top">
                                    <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['smarttrace:partner: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-tab-pane>
            <el-tab-pane label="授权应用" name="tab2" disabled>
                <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="handleAddApp" v-hasPermi="['smarttrace:partner:add']">新增应用授权</el-button>
                            </el-col>
                            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
                        </el-row>
                    </template>
                    <el-table v-loading="loading" :data="applicationList" border>
                        <el-table-column type="index" label="序号" width="55" align="center" />
                        <el-table-column label="应用名称" align="center" prop="applicationName" />
                        <el-table-column label="图标" align="center" prop="icon">
                            <template #default="{ row }">
                                <ImagePreview :src="row.icon"></ImagePreview>
                            </template>
                        </el-table-column>
                        <el-table-column label="背景" align="center" prop="bgUrl">
                            <template #default="{ row }">
                                <ImagePreview :src="row.bgUrl"></ImagePreview>
                            </template>
                        </el-table-column>
                        <el-table-column label="跳转地址" align="center" prop="url" />
                        <el-table-column label="应用类型" align="center" prop="type">
                            <template #default="{ row }">
                                <dict-tag :options="application_type" :value="row.type"></dict-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="前置条件" width="200">
                            <template #default="{ row }">
                                <div v-for="item in row.precondition" style="display: flex;">
                                    <div>
                                        <dict-tag :options="enterprise_type" :value="item.cpyType" />
                                    </div>
                                    -
                                    <div>
                                        <dict-tag :options="industry_type" :value="item.industryType" />
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="状态" align="center" width="180" prop="status">
                            <template #default="{ row }">
                                <el-switch v-model="row.status" active-value="1" @change="changeStatus($event, row.id)" inactive-value="0" active-text="启用" inactive-text="未启用" />
                            </template>
                        </el-table-column>
                        <el-table-column label="授权开始日期" align="center" prop="startAt" />
                        <el-table-column label="授权结束日期" align="center" prop="endAt" />
                        <el-table-column label="备注" align="center" prop="remark" />
                        <el-table-column label="应用ID" align="center" prop="id" />
                        <el-table-column label="创建时间" align="center" prop="createTime" width="120">
                            <template #default="scope">
                                <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
                            <template #default="scope">
                                <el-tooltip content="编辑" placement="top">
                                    <el-button link type="primary" icon="Edit" @click="handleEdit(scope.row)" v-hasPermi="['smarttrace:application:edit']"></el-button>
                                </el-tooltip>
                                <el-tooltip content="查看" placement="top">
                                    <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['smarttrace:application:edit']"></el-button>
                                </el-tooltip>
                                <el-tooltip content="删除" placement="top">
                                    <el-button link type="primary" icon="Delete" @click="handleDeleteApp(scope.row)" v-hasPermi="['smarttrace:application:remove']"></el-button>
                                </el-tooltip>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-card>
            </el-tab-pane>
        </el-tabs>
        <!-- 添加或修改合作伙伴信息对话框 -->
        <el-dialog :close-on-click-modal="false" :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
            <el-form ref="partnerFormRef" :model="form" :rules="rules" label-width="108px">
                <el-form-item label="合作伙伴名称" prop="partnerName">
                    <el-input v-model="form.partnerName" placeholder="请输入合作伙伴名称" />
                </el-form-item>
                <el-form-item label="合作伙伴编码" prop="partnerCode">
                    <el-input v-model="form.partnerCode" placeholder="请输入合作伙伴编码" />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" placeholder="请输入备注" />
                </el-form-item>
            </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 :close-on-click-modal="false" title="合作伙伴应用授权" v-model="appAddvisible" width="600px" append-to-body>
            <el-form ref="appAddFormRef" :model="appAddForm" :rules="appAddRules" label-width="108px" :disabled="appAddDisabled">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="原始应用" prop="originId">
                            <el-select v-model="appAddForm.originId" style="width: 100%;" placeholder="请选择原始应用">
                                <el-option v-for="app in originApps" :key="app.id" :label="app.applicationName" :value="(app.id as number)" @click.native="handleOriginChange(app)" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="应用类型" prop="type">
                            <el-select v-model="appAddForm.type" style="width: 100%;" placeholder="请选择应用类型" disabled>
                                <el-option v-for="dict in application_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="应用名称" prop="applicationName">
                    <el-input v-model="appAddForm.applicationName" placeholder="请输入应用名称" />
                </el-form-item>
                <el-form-item label="跳转地址" prop="url">
                    <el-input v-model="appAddForm.url" placeholder="跳转地址" />
                </el-form-item>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="图标" prop="icon">
                            <div>
                                <UploadAvatar title="应用图标" v-model="appAddForm.icon"></UploadAvatar>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="背景" prop="bgUrl">
                            <PhotoUpload v-model="appAddForm.bgUrl"></PhotoUpload>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="按钮颜色" prop="btnConf">
                            <el-input v-model="appAddForm.btnConf"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="授权开始日期" prop="startAt">
                            <el-date-picker v-model="appAddForm.startAt" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="授权结束日期" prop="endAt">
                            <el-date-picker v-model="appAddForm.endAt" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="appAddForm.remark" placeholder="请输入备注" />
                </el-form-item>
                <el-form-item label="按钮配置" prop="btnConf">
                    <el-input v-model="appAddForm.btnConf" placeholder="请输入按钮配置" />
                </el-form-item>
                <el-divider>前置条件（任意一个）</el-divider>
                <div class="cpy-container" v-loading="loading">
                    <div class="cpy-item" v-for="(item, index) in appAddForm.precondition">
                        <el-form-item label="企业类型" :prop="`precondition.${index}.cpyType`" :rules="{ required: true, message: '企业类型不能为空', trigger: 'blur' }">
                            <el-select v-model="item.cpyType" placeholder="企业类型">
                                <el-option v-for="dict in enterprise_type" :label="dict.label" :value="dict.value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="行业类别" :prop="`precondition.${index}.industryType`" :rules="{ required: true, message: '行业类别不能为空', trigger: 'blur' }">
                            <el-select v-model="item.industryType" placeholder="行业类别">
                                <el-option v-for="dict in industry_type" :label="dict.label" :value="dict.value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-button type="text" icon="remove" @click="handleRemovePrecondition(index)"></el-button>
                    </div>
                </div>
                <span v-show="appAddForm.precondition.length == 0">无需前置条件</span>
                <div style="display: flex;">
                    <el-button type="primary" style="flex:1" @click="handleAddPrecondition">添加条件</el-button>
                </div>
                <el-divider>密钥信息</el-divider>
                <el-form-item label="应用私钥" prop="partnerPriKey">
                    <el-input v-model="appAddForm.keyInfo.partnerPriKey" placeholder="请输入应用私钥" />
                </el-form-item>
                <el-form-item label="应用公钥" prop="partnerPubKey">
                    <el-input v-model="appAddForm.keyInfo.partnerPubKey" placeholder="请输入应用公钥" />
                </el-form-item>
                <el-form-item label="小程序appid" prop="appid">
                    <el-input v-model="appAddForm.keyInfo.appid" placeholder="请输入小程序appid" />
                </el-form-item>
                <el-form-item label="小程序secret" prop="secret">
                    <el-input v-model="appAddForm.keyInfo.secret" placeholder="请输入小程序secret" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button :loading="buttonLoading" type="primary" @click="submitAppAddForm">确 定</el-button>
                    <el-button @click="cancelAppAdd">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="Partner" lang="ts">
import { listPartner, getPartner, delPartner, addPartner, updatePartner } from '@/api/permission/partner';
import { listApplicationOther, listApplicationQx, addApplication, ApplicationOnshelf, ApplicationLeaveshelf, delApplication, updateApplication } from "@/api/permission/application";
import { PartnerVO, PartnerQuery, PartnerForm } from '@/api/permission/partner/types';
import { ApplicationVO, ApplicationForm } from "@/api/permission/application/types";
import { parseTime } from '@/utils/ruoyi'
import { UploadAvatar } from '@/views/components';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const partnerList = ref<PartnerVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const { application_type, enterprise_type, industry_type } = toRefs<any>(proxy?.useDict('application_type', 'industry_type', 'enterprise_type'))
const queryFormRef = ref<ElFormInstance>();
const partnerFormRef = ref<ElFormInstance>();

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

const initFormData: PartnerForm = {
  id: undefined,
  partnerName: undefined,
  partnerCode: undefined,
  key: undefined,
  startAt: undefined,
  endAt: undefined,
  status: undefined,
  remark: undefined,
}
const data = reactive<PageData<PartnerForm, PartnerQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    partnerName: undefined,
    partnerCode: undefined,
    key: undefined,
    startAt: undefined,
    endAt: undefined,
    status: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "ID不能为空", trigger: "blur" }
    ],
    partnerName: [
      { required: true, message: "合作伙伴名称不能为空", trigger: "blur" }
    ],
  }
});

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

/** 查询合作伙伴信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listPartner(queryParams.value);
  partnerList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

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

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

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

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



/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加合作伙伴信息";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: PartnerVO) => {
  reset();
  const _id = row?.id as number
  const res = await getPartner(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改合作伙伴信息";
}

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

/** 删除按钮操作 */
const handleDelete = async (row?: PartnerVO) => {
  const _ids = row?.id as number
  await proxy?.$modal.confirm('是否确认删除合作伙伴信息编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delPartner(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('permission/partner/export', {
    ...queryParams.value
  }, `partner_${new Date().getTime()}.xlsx`)
}
const activeTab = ref('tab1')
/** tab2 */
const applicationList = ref<ApplicationVO[]>([])
const originApps = ref<ApplicationVO[]>([])
const partnerId = ref<number | undefined>(undefined)
const appAddDisabled = ref(false)
const viewApps = async (row: any) => {
  partnerId.value = row.id
  loading.value = true
  const res = await listApplicationOther({ partnerId: row.id || '', pageNum: 1, pageSize: 100 }).finally(() => loading.value = false)
  applicationList.value = res.rows
  activeTab.value = 'tab2'
}

const handleDeleteApp = async (row: ApplicationVO) => {
  await proxy?.$modal.confirm('是否确认删除应用？').finally(() => loading.value = false);
  await delApplication(row.id || '');
  proxy?.$modal.msgSuccess("删除成功");
  viewApps({ id: partnerId.value })
}
const changeStatus = async (event: string, id: string) => {
  loading.value = true;
  const fun = +event ? ApplicationOnshelf(id) : ApplicationLeaveshelf(id)
  await fun
  viewApps({ id: partnerId.value })
}
/**
 * 弹框相关
 */
const initAppAddForm = (): ApplicationForm => ({
  id: undefined,
  applicationName: undefined,
  icon: undefined,
  url: undefined,
  type: undefined,
  remark: undefined,
  startAt: new Date(),
  endAt: undefined,
  originId: undefined,
  partnerId: partnerId.value,
  keyInfo: {},
  precondition: []
})
const appAddForm = ref(initAppAddForm())
const appAddFormRef = ref<ElFormInstance>();
const appAddRules = {
  applicationName: [{ required: true, message: "应用名称不能为空", trigger: "blur" }],
  originId: [{ required: true, message: "原始应用不能为空", trigger: "blur" }],
  type: [{ required: true, message: "应用名称不能为空", trigger: "blur" }],
  partnerId: [{ required: true, message: "合作伙伴不能为空", trigger: "blur" }],
  startAt: [{ required: true, message: "开始日期不能为空", trigger: "blur" }],
}
/** 添加前置条件 */
const handleAddPrecondition = () => {
  appAddForm.value.precondition.push({ cpyType: '1', industryType: '1' })
}
const handleRemovePrecondition = (index: number) => {
  appAddForm.value.precondition.splice(index, 1)
}
const appAddvisible = ref(false)
const resetAppAdd = () => {
  appAddDisabled.value = false
  appAddForm.value = initAppAddForm()
}
const cancelAppAdd = () => {
  appAddvisible.value = false
}
const handleAddApp = () => {
  resetAppAdd()
  appAddvisible.value = true
}
const handleEdit = (row: ApplicationVO) => {
  resetAppAdd()
  Object.assign(appAddForm.value, row)
  appAddvisible.value = true
}
const handleView = (row: ApplicationVO) => {
  resetAppAdd()
  appAddDisabled.value = true
  Object.assign(appAddForm.value, row)
  appAddvisible.value = true
}
const submitAppAddForm = async () => {
  const valid = await appAddFormRef.value?.validate()
  if (valid) {
    buttonLoading.value = true
    const fun = appAddForm.value.id ? updateApplication(appAddForm.value) : addApplication(appAddForm.value)
    await fun.finally(() => buttonLoading.value = false)
    appAddvisible.value = false
    proxy?.$modal.alert("操作成功")
    viewApps({ id: appAddForm.value.partnerId })
  }
}
const loadApps = async () => {
  const res = await listApplicationQx({ pageNum: 1, pageSize: 100 });
  originApps.value = res.rows;
}
const diffApps = computed(() => {
  return originApps.value.filter(x => !applicationList.value.map(o => o.originId).includes(x.id as number))
})
const handleOriginChange = (app: ApplicationVO) => {
  appAddForm.value.applicationName = app.applicationName
  appAddForm.value.type = app.type
  appAddForm.value.icon = app.icon
  appAddForm.value.bgUrl = app.bgUrl
  appAddForm.value.precondition = app.precondition
}
onMounted(() => {
  getList();
  loadApps();

});
</script>
<style scoped>
.cpy-container {
  margin-top: 20px;
  margin-bottom: 20px;

  .cpy-item {
    display: flex;
    justify-content: space-between;
    align-items: baseline;
  }
}
</style>
