<template>
  <div class="p-2">
    <el-card shadow="never">
      <el-tabs v-model="activeTab" type="border-card">
        <el-tab-pane label="会员信息" name="meberInfo">
          <el-form ref="memberFormRef" :model="form" :rules="rules">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="企业名称" prop="cpyName">
                  <el-input v-model="form.cpyName" placeholder="请输入企业名称" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="法人姓名" prop="legalPersonName">
                  <el-input v-model="form.legalPersonName" placeholder="请输入法人姓名" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="法人电话" prop="legalPersonPhone">
                  <el-input v-model="form.legalPersonPhone" placeholder="请输入法人电话" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="法人职务" prop="legalPersonPosition">
                  <el-input v-model="form.legalPersonPosition" placeholder="请输入法人职务" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="法人身份证正面图片" prop="legalPersonIdFront">
                  <image-upload v-model="form.legalPersonIdFront" :limit="1" :isString="true" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="法人身份证背面图片" prop="legalPersonIdBack">
                  <image-upload v-model="form.legalPersonIdBack" :limit="1" :isString="true" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="申请会员等级" prop="applyLevel">
                  <el-input v-model="form.applyLevel" placeholder="请输入申请会员等级" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="form.email" placeholder="请输入邮箱" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="主管部门" prop="department">
                  <el-input v-model="form.department" placeholder="请输入主管部门" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="总资产" prop="totalAssets">
                  <el-input v-model="form.totalAssets" placeholder="请输入总资产" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="单位简介" prop="introduction">
                  <el-input v-model="form.introduction" type="textarea" placeholder="请输入内容" :rows="5" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="入会目的" prop="membershipPurpose">
                  <el-input v-model="form.membershipPurpose" type="textarea" placeholder="请输入内容" :rows="5" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="会员等级" prop="vipLevel">
                  <el-select v-model="form.vipLevel" placeholder="请选择" clearable>
                    <el-option v-for="dict in vip_level" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="开始时间" prop="startDate">
                  <el-date-picker clearable v-model="form.startDate" type="date" value-format="YYYY-MM-DD"
                    placeholder="请选择开始时间" style="width: 100%;">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="结束时间" prop="endDate">
                  <el-date-picker clearable v-model="form.endDate" type="date" value-format="YYYY-MM-DD"
                    placeholder="请选择结束时间" style="width: 100%;">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="审核信息" prop="reviewMsg">
                  <el-input v-model="form.reviewMsg" placeholder="请输入审核信息" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="审核人" prop="reviewBy">
                  <el-input v-model="form.reviewBy" placeholder="请输入审核人" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="审核时间" prop="reviewTime">
                  <el-date-picker clearable v-model="form.reviewTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="请选择审核时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-table v-loading="loading" :data="form.plantingInfo">
              <el-table-column label="品种名称" align="center" prop="variety" width="220" />
              <el-table-column label="种植面积" align="center" prop="plantingArea" />
              <el-table-column label="种植地点" align="center" prop="plantingPlace" width="150" />
            </el-table>
            <el-row :gutter="20">
              <el-col>
                <el-form-item label="荣誉证书" prop="companyCertificate">
                  <image-upload v-model="form.companyCertificate" :limit="10" :isString="true" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div class="dialog-footer" style="text-align: center;">
            <el-button :loading="buttonLoading" type="primary" @click="submitForm">提 交</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-tab-pane>

        <el-tab-pane label="缴费记录" name="payMentFormRef">
          <div class="search">
            <el-form :model="vipPaymentQueryParams" ref="vipPaymentFormRef" :inline="true" label-width="68px">
              <el-form-item label="续费类型" prop="paymentType">
                <el-select v-model="vipPaymentQueryParams.paymentType" placeholder="请选择" clearable style="width: 240px">
                  <el-option v-for="dict in payment_type" :key="dict.value" :label="dict.label" :value="dict.value"
                    @keyup.enter="handleQueryVipPayment" />
                </el-select>
              </el-form-item>
              <el-form-item label="开票状态" prop="invoiceStatus">
                <el-select v-model="vipPaymentQueryParams.invoiceStatus" placeholder="请选择" clearable style="width: 240px">
                  <el-option v-for="dict in invoice_status" :key="dict.value" :label="dict.label" :value="dict.value"
                    @keyup.enter="handleQueryVipPayment" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQueryVipPayment">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </div>

          <el-card shadow="never">
            <el-table v-loading="loading" :data="vipPaymentList">
              <el-table-column label="缴费金额" align="center" prop="paymentAmount" />
              <el-table-column label="缴费时间" align="center" prop="paymentTime" width="180">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.paymentTime, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="缴费方式" align="center" prop="paymentType">
                <template #default="scope">
                  <dict-tag :value="scope.row.paymentType" :options="payment_type" />
                </template>
              </el-table-column>
              <el-table-column label="缴费状态" align="center" prop="paymentStatus">
                <template #default="scope">
                  <dict-tag :value="scope.row.paymentStatus" :options="payment_status" />
                </template>
              </el-table-column>
              <el-table-column label="缴费备注" align="center" prop="paymentRemark" />
              <el-table-column label="开票状态" align="center" prop="invoiceStatus">
                <template #default="scope">
                  <dict-tag :value="scope.row.invoiceStatus" :options="invoice_status" />
                </template>
              </el-table-column>
              <el-table-column label="发票" align="center" prop="invoiceUrl">
                <template #default="scope">
                  <el-link :underline="false" type="primary" :href="scope.row.invoiceUrlAddr" target="_blank"
                    v-if="scope.row.invoiceStatus != 0">查看发票</el-link>
                  <el-button link type="primary" @click="showUploadInvoice(scope.row)"
                    v-hasPermi="['dgtmedicine:vipPayment:edit']" v-if="scope.row.invoiceStatus == 0">
                    上传发票
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column label="创建人" align="center" prop="createByName" />
              <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="Delete" @click="handleDelete(scope.row)"
                      v-hasPermi="['dgtmedicine:vipPayment: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-dialog :close-on-click-modal="false" :title="dialogUpload.title" v-model="dialogUpload.visible"
            width="500px" append-to-body>
            <el-form ref="payMentFormRef" :model="paymentFrom" :rules="rules">
              <el-row :gutter="20">
                <file-upload v-model="paymentFrom.invoiceUrl" :limit="1" :isString="true" />
              </el-row>
            </el-form>
            <template #footer>
              <div class="dialog-footer">
                <el-button :loading="buttonLoading" type="primary" @click="confirmUpload">确 定</el-button>
                <el-button @click="cancelUpload">取 消</el-button>
              </div>
            </template>
          </el-dialog>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>

</template>

<script setup name="Member" lang="ts">
import { listMember, getMember, addMember, updateMember } from '@/api/dgtmedicine/member';
import { MemberVO, MemberQuery, MemberForm } from '@/api/dgtmedicine/member/types';
import { listVipPayment, getVipPayment, delVipPayment, uploadInvoice, updateVipPayment } from '@/api/dgtmedicine/vipPayment';
import { VipPaymentVO, VipPaymentQuery, VipPaymentForm } from '@/api/dgtmedicine/vipPayment/types';
import { useRouter } from 'vue-router';

const { query } = useRoute();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { vip_level, invoice_status, payment_status, payment_type } =
  toRefs<any>(proxy?.useDict("vip_level", "invoice_status", "payment_status", "payment_type"));
const router = useRouter();

const vipPaymentList = ref<VipPaymentVO[]>([]);
const memberList = ref<MemberVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const refuseShow = ref(false);
const ids = ref<Array<string | number>>([]);
const memberId = ref('');
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const approvalLogFormRef = ref<ElFormInstance>();
const activeTab = ref('meberInfo')
const vipPaymentFormRef = ref<ElFormInstance>();
const memberFormRef = ref<ElFormInstance>();
const payMentFormRef = ref<ElFormInstance>();

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

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

const initFormData: MemberForm = {
  id: undefined,
  cpyName: undefined,
  legalPersonName: undefined,
  legalPersonPhone: undefined,
  legalPersonPosition: undefined,
  legalPersonIdFront: undefined,
  legalPersonIdBack: undefined,
  companyCertificate: undefined,
  email: undefined,
  department: undefined,
  totalAssets: undefined,
  introduction: undefined,
  regType: undefined,
  membershipPurpose: undefined,
  plantingInfo: [
    { variety: undefined, plantingArea: undefined, plantingPlace: 0, paymentDesc: undefined }
  ],
  vipLevel: undefined,
  startDate: undefined,
  endDate: undefined,
  reviewStatus: undefined,
  reviewMsg: undefined,
  reviewBy: undefined,
  reviewTime: undefined,
  partnerId: undefined,
  cpyBusType: undefined,
  applyLevel: undefined
}


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

  }
});

const vipPaymentData = reactive<PageData<VipPaymentForm, VipPaymentQuery>>({
  form: { ...initPayFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    memberId: undefined,
    paymentAmount: undefined,
    paymentTime: undefined,
    paymentType: undefined,
    paymentStatus: undefined,
    paymentRemark: undefined,
    invoiceStatus: undefined,
    invoiceUrl: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "ID不能为空", trigger: "blur" }
    ],
    invoiceUrl: [
      { required: true, message: "发票地址不能为空", trigger: "blur" }
    ]
  }
});


const { queryParams, form, rules } = toRefs(data);
const { queryParams: vipPaymentQueryParams, form: paymentFrom } = toRefs(vipPaymentData);

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

/** 搜索按钮操作 */
const handleQueryVipPayment = () => {
  vipPaymentQueryParams.value.pageNum = 1;
  getVipPaymentList();
}

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

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


/** 查询会员缴费记录列表 */
const getVipPaymentList = async () => {
  loading.value = true;
  vipPaymentQueryParams.value.memberId = memberId.value;
  const res = await listVipPayment(vipPaymentQueryParams.value);
  vipPaymentList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

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

/** 上传发票 */
const showUploadInvoice = async (row?: VipPaymentVO) => {
  dialogUpload.title = '上传发票';
  dialogUpload.visible = true;
  paymentFrom.value = { ...initPayFormData, id: row?.id };
}

/**取消审批弹框 */
const cancelUpload = () => {
  dialogUpload.visible = false
}

/**审批弹框 */
const confirmUpload = () => {
  payMentFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      await uploadInvoice({ id: paymentFrom.value.id, invoiceUrl: paymentFrom.value.invoiceUrl }).finally(() => buttonLoading.value = false);
      proxy?.$modal.msgSuccess("操作成功");
      dialogUpload.visible = false
      getVipPaymentList();
    }
  });
}

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

/** 提交按钮 */
const submitForm = () => {
  memberFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (!Array.isArray(form.value.companyCertificate)) {
        var companyCertificateList = form.value.companyCertificate.split(',');
        form.value.companyCertificate = companyCertificateList;
      }
      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 getMemberInfo();
    }
  });
}

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


onMounted(() => {
  memberId.value = (query.memberId as string)
  getMemberInfo();
  getVipPaymentList();
});
</script>
