<template>
  <div class="p-2">
    <div class="search" v-show="showSearch">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
        <el-form-item label="企业名称" prop="cpyName">
          <el-input v-model="queryParams.cpyName" placeholder="请输入企业名称" clearable style="width: 240px"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="日期范围" prop="dateRange">
          <el-date-picker clearable v-model="queryParams.dateRange" type="daterange" range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" @change="handleDateRangeChange" />
        </el-form-item>
        <el-form-item label="审核状态" prop="reviewStatus">
          <el-select v-model="queryParams.reviewStatus" placeholder="请选择" clearable style="width: 240px">
            <el-option v-for="dict in cpy_res_status" :key="dict.value" :label="dict.label" :value="dict.value"
              @keyup.enter="handleQuery" />
          </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>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="20" class="mb8">
          <el-col :span="2" v-for="level in memberLevelCountList" :key="level.type">
            <el-button type="text" @click="handleQuery(level)"
              :style="{ fontWeight: queryParams.vipLevel === level.type ? 'bold' : 'normal', color: queryParams.vipLevel === level.type ? 'black' : 'inherit' }">{{
                level.name }}({{ level.num }})</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <vxe-table :loading="loading" border :data="memberList">
        <vxe-column title="企业名称" align="center" field="cpyName" width="220" />
        <vxe-column title="法人姓名" align="center" field="legalPersonName" />
        <vxe-column title="法人电话" align="center" field="legalPersonPhone" width="150" />
        <vxe-column title="当前等级" align="center" field="vipLevel">
          <template #default="scope">
            <dict-tag :value="scope.row.vipLevel" :options="vip_level" />
          </template>
        </vxe-column>
        <vxe-column title="申请等级" align="center" field="applyLevel">
          <template #default="scope">
            <dict-tag :value="scope.row.applyLevel" :options="vip_level" />
          </template>
        </vxe-column>
        <vxe-column title="开始时间" align="center" field="startDate" width="100">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
          </template>
        </vxe-column>
        <vxe-column title="结束时间" align="center" field="endDate" width="100">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
          </template>
        </vxe-column>
        <!-- <vxe-column label="业务类型" align="center" prop="cpyBusType" /> -->
        <vxe-column title="审核状态" align="center" field="reviewStatus">
          <template #default="scope">
            <dict-tag :value="scope.row.reviewStatus" :options="cpy_res_status" />
          </template>
        </vxe-column>
        <vxe-column title="审核信息" align="center" field="reviewMsg" />
        <vxe-column title="审核时间" align="center" field="reviewTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.reviewTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </vxe-column>
        <vxe-column title="创建时间" align="center" field="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </vxe-column>
        <!-- <vxe-column label="更新时间" align="center" prop="updateTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </vxe-column> -->
        <vxe-column title="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" @click="showApp(scope.row)"
              v-if="scope.row.reviewStatus == '0'">审批</el-button>
            <el-button link type="primary" @click="memberDetail(scope.row)"
              v-if="scope.row.reviewStatus != '0'">详情</el-button>
          </template>
        </vxe-column>
      </vxe-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="dialogApproval.title" v-model="dialogApproval.visible"
      width="1200px" append-to-body>
      <el-form ref="memberFormRef" :model="form" :rules="rules">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="企业名称" prop="cpyName">
              <el-text v-model="form.cpyName">{{ form.cpyName }}</el-text>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="法人姓名" prop="legalPersonName">
              <el-text>{{ form.legalPersonName }}</el-text>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="法人电话" prop="legalPersonPhone">
              <el-text>{{ form.legalPersonPhone }}</el-text>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="法人职务" prop="legalPersonPosition">
              <el-text>{{ form.legalPersonPosition }}</el-text>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="法人身份证正面图片" prop="legalPersonIdFront">
              <el-image :src="form.legalPersonIdFront" style="width: 100px; height: 100px" show-progress
                :preview-src-list="[form.legalPersonIdFront]" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="法人身份证背面图片" prop="legalPersonIdBack">
              <el-image :src="form.legalPersonIdBack" style="width: 100px; height: 100px" show-progress
                :preview-src-list="[form.legalPersonIdBack]" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="申请会员等级" prop="applyLevel">
              <dict-tag :value="form.applyLevel" :options="vip_level" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="邮箱" prop="email">
              <el-text>{{ form.email }}</el-text>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="主管部门" prop="department">
              <el-text>{{ form.department }}</el-text>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="总资产" prop="totalAssets">
              <el-text>{{ form.totalAssets }}</el-text>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单位简介" prop="introduction">
              <el-text>{{ form.introduction }}</el-text>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入会目的" prop="membershipPurpose">
              <el-text>{{ form.membershipPurpose }}</el-text>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="当前会员等级" prop="vipLevel">
              <dict-tag :value="form.vipLevel" :options="vip_level" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="开始时间" prop="startDate">
              <el-text>{{ form.startDate }}</el-text>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="结束时间" prop="endDate">
              <el-text>{{ form.endDate }}</el-text>
            </el-form-item>
          </el-col>
        </el-row>
        <el-table v-loading="loading" :data="form.plantingInfo">
          <vxe-column label="品种名称" align="center" prop="variety" />
          <vxe-column label="种植面积" align="center" prop="plantingArea" />
          <vxe-column label="种植地点" align="center" prop="plantingPlace" />
        </el-table>
        <el-row :gutter="20">
          <el-col>
            <el-form-item label="荣誉证书" prop="companyCertificate">
              <el-image :src="form.companyCertificate" style="width: 100px; height: 100px" show-progress
                :preview-src-list="form.companyCertificate" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-form ref="approvalLogFormRef" :model="approvalForm" :rules="approvalRules" label-width="80px">
        <el-form-item label="审批类型" prop="reviewStatus">
          <el-select v-model="approvalForm.reviewStatus" placeholder="请选择" clearable style="width: 100%"
            @change="showRefuse">
            <template v-for="dict in cpy_res_status">
              <el-option v-if="dict.value != '0'" :key="dict.value" :label="dict.label" :value="dict.value" />
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="审批理由" prop="msg" v-if="refuseShow">
          <el-input type="textarea" v-model="approvalForm.reviewMsg" placeholder="请输入拒绝理由" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="confirmApp">确 定</el-button>
          <el-button @click="cancelApp">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>

</template>

<script setup name="Member" lang="ts">
import { listMember, getMember, delMember, addMember, updateMember, countLevelMember } from '@/api/dgtmedicine/member';
import { approvalMember } from '@/api/dgtmedicine/approvalLog';
import { MemberVO, MemberQuery, MemberForm, MemberLevelCountVO } from '@/api/dgtmedicine/member/types';
import { ApprovalLogQuery, ApprovalLogForm } from '@/api/dgtmedicine/approvalLog/types';
import { useRouter } from 'vue-router';
const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { cpy_res_status, vip_level } = toRefs<any>(proxy?.useDict("cpy_res_status", "vip_level"));

const memberList = ref<MemberVO[]>([]);
const memberLevelCountList = ref<MemberLevelCountVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const refuseShow = ref(false);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const approvalLogFormRef = ref<ElFormInstance>();

const queryFormRef = ref<ElFormInstance>();
const memberFormRef = ref<ElFormInstance>();

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

const initFormApprovalData: ApprovalLogForm = {
  id: undefined,
  targetType: undefined,
  reviewStatus: '1',
  reviewMsg: undefined
}

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

const approvalData = reactive<PageData<ApprovalLogForm, ApprovalLogQuery>>({
  form: { ...initFormApprovalData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    targetType: undefined,
    targetId: undefined,
    res: undefined,
    msg: undefined,
    params: {
    }
  },
  rules: {
  }
});

const initFormData: MemberForm = {
  id: undefined,
  cpyName: '',
  legalPersonName: '',
  legalPersonPhone: '',
  legalPersonPosition: '',
  legalPersonIdFront: '',
  legalPersonIdBack: '',
  companyCertificate: '',
  email: '',
  department: '',
  totalAssets: '',
  introduction: '',
  regType: '',
  membershipPurpose: '',
  plantingInfo: [],
  vipLevel: '',
  startDate: '',
  endDate: '',
  reviewStatus: '',
  reviewMsg: '',
  reviewBy: '',
  reviewTime: '',
  partnerId: '',
  cpyBusType: '',
  applyLevel: ''
}
const data = reactive<PageData<MemberForm, MemberQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    cpyName: '',
    legalPersonName: '',
    legalPersonPhone: '',
    legalPersonPosition: '',
    legalPersonIdFront: '',
    legalPersonIdBack: '',
    companyCertificate: '',
    email: '',
    department: '',
    totalAssets: '',
    introduction: '',
    regType: '',
    membershipPurpose: '',
    plantingInfo: '',
    vipLevel: '',
    startDate: '',
    endDate: '',
    reviewStatus: '',
    reviewMsg: '',
    reviewBy: '',
    reviewTime: '',
    partnerId: '',
    cpyBusType: '',
    applyLevel: '',
    params: {
    }
  },
  rules: {

  }
});

const { queryParams, form, rules } = toRefs(data);
const { form: approvalForm, rules: approvalRules } = toRefs(approvalData);


/**动态显示审批理由 */
const showRefuse = (res: any) => {
  if (res == "2") {
    refuseShow.value = true
    return
  }
  refuseShow.value = false
}

/** 查询会员信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listMember(queryParams.value);
  memberList.value = res.rows;
  total.value = res.total;
  loading.value = false;

}

/** 查询会员信息列表 */
const getMemberLevelList = async () => {
  loading.value = true;
  const res = await countLevelMember(queryParams.value);
  memberLevelCountList.value = res.data;
  loading.value = false;
}

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

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

/** 搜索按钮操作 */
const handleQuery = (level?: any) => {
  queryParams.value.pageNum = 1;
  if (level !== undefined && level !== null && level.type !== 'click') {
    queryParams.value.vipLevel = level.type;
  }
  getList();
}


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

/**审批弹框 */
const showApp = (row: any) => {
  approvalReset()
  dialogApproval.visible = true
  approvalForm.value.id = row.id
  getMemberInfo(row.id)
}

/** 修改按钮操作 */
const getMemberInfo = async (memberId: string) => {
  reset();
  const res = await getMember(memberId);
  Object.assign(form.value, res.data);
}

const memberDetail = (row: any) => {
  router.push({ path: `/szyy/member-detail`, query: { memberId: row.id } });
}

/** 处理日期范围变化 */
const handleDateRangeChange = (value: [string, string]) => {
  if (value && value.length === 2) {
    queryParams.value.startDate = value[0];
    queryParams.value.endDate = value[1];
  } else {
    queryParams.value.startDate = undefined;
    queryParams.value.endDate = undefined;
  }
  handleQuery();
}

/** 审批表单重置 */
const approvalReset = () => {
  refuseShow.value = false
  approvalForm.value = { ...initFormApprovalData };
  approvalLogFormRef.value?.resetFields();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: MemberVO[]) => {
  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?: MemberVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getMember(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改会员信息";
}

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

/**取消审批弹框 */
const cancelApp = () => {
  approvalReset()
  dialogApproval.visible = false
}


/**审批弹框 */
const confirmApp = () => {
  approvalLogFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      await approvalMember(approvalForm.value).finally(() => buttonLoading.value = false);
      proxy?.$modal.msgSuccess("操作成功");
      dialogApproval.visible = false
      getList();
    }
  });
}

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

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

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