<template>
 <!-- Modal -->
 <a-modal v-model:visible="modalVisible" fullscreen title="提现详情" title-align="start" :footer="false"
       @cancel="handleClose">
      <div class="titlebox">
        <div class="bar"></div>
        <div class="name">医生信息</div>
      </div>
      <a-form :model="modalForm"    ref="modalFormRef" :auto-label-width="true">
        <a-row :gutter="24" style="margin-top: 35px;">
          <a-col :span="12">
            <a-form-item field="avatar" label="医生姓名：">
              <span>{{modalForm.doctor_name}} </span>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="idCard" label="身份证号：" >
              <div class="box" v-show="!showEye">
                <div class="cardNum">{{modalForm.doctor_card_num_mask}}</div>
                <icon-eye-invisible class="eye" @click="handelDecryptCard(modalForm.doctor_user_id,'')" />
              </div>
              <div class="box" v-show="showEye">
                <div class="cardNum">{{id_card_num}}</div>
                <icon-eye class="eye" @click="()=>{showEye=false}" />
              </div>
            </a-form-item>
          </a-col>
        </a-row>
  
        <a-divider />
        <div class="titlebox">
        <div class="bar"></div>
        <div class="name">银行信息</div>
      </div>
        <a-row :gutter="24" style="margin-top: 35px;">
          <a-col :span="12">
            <a-form-item field="avatar" label="银行卡号：">
              <span>{{modalForm.bank_card_code}}</span>
            </a-form-item>
          </a-col>
          <a-col :span="12">
      
            <a-form-item field="idCard" label="提现状态：" >
               
              <div v-if="modalForm.examine_status==1 && modalForm.payment_status==0">待结算</div>
              <div v-else-if="modalForm.examine_status==2 && modalForm.payment_status==0">结算中</div>
              <div v-else-if="modalForm.examine_status==2 && modalForm.payment_status==1">结算成功</div>
              <div v-else-if="modalForm.examine_status==3 ">结算失败</div>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item field="idCard" label="所在城市：" >
              <span v-if="modalForm.doctor_withdrawal_bank">{{modalForm.doctor_withdrawal_bank.province}}{{modalForm.doctor_withdrawal_bank.city}}{{modalForm.doctor_withdrawal_bank.county}}</span>
              <span v-else>-</span>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="idCard" label="开户行：" >
              <span v-if="modalForm.doctor_withdrawal_bank">{{modalForm.doctor_withdrawal_bank.basic_bank.bank_name
}}</span>
              <span v-else>-</span>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24" v-if="modalForm.examine_fail_reason">
          <a-col :span="12">
            <a-form-item field="idCard" label="拒绝理由：" >
              <span >{{modalForm.doctor_withdrawal_bank.province}}{{modalForm.doctor_withdrawal_bank.city}}{{modalForm.doctor_withdrawal_bank.county}}</span>
            </a-form-item>
          </a-col>
          
        </a-row>
        <a-divider />
        <div class="titlebox">
          <div class="bar"></div>
          <div class="name">账户信息</div>
        </div>
        <a-row :gutter="24" style="margin-top: 35px;">
          <a-col :span="12">
            <a-form-item field="idCard" label="申请时间：" >
              <div>{{modalForm.created_at}}</div>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="idCard" label="确认账单时间：" >
              <div v-if="parseTime(modalForm.examine_time)">{{parseTime(modalForm.examine_time)}}</div>
              <div v-else>-</div>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24" >
          <a-col :span="12">
            <a-form-item field="idCard" label="应提现金额：" >
              <div>{{modalForm.applied_withdrawal_amount}}元</div>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="idCard" label="实际提现金额：" >
              <div>{{modalForm.actual_withdrawal_amount}}元</div>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24" >
          <a-col :span="12">
            <a-form-item field="idCard" label="分成比例：" >
              <div>平台2.5/医生7.5</div>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="idCard" label="个人所得税：" >
              <div>{{modalForm.income_tax}}元</div>
              <a-button type="primary" @click="()=>okVisible=true" style="margin-left:20px;" v-has="'admin:sysFinancialRecord:tax'" :disabled="!(modalForm.examine_status==1 && modalForm.payment_status==0)">纠正个人所得税</a-button>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24" v-if="parseTime(modalForm.payment_time)">
          <a-col :span="12">
            <a-form-item field="idCard" label="打款时间：" >
              <div>{{parseTime(modalForm.payment_time)}}</div>
            </a-form-item>
          </a-col>
        </a-row>
        <a-divider /> 
      
        <div class="titlebox">
          <div class="bar"></div>
          <div class="name">订单记录</div>
        </div>
         <!-- action -->
         <div class="action" style="margin-top: 35px;">
          <a-space>
            <a-button v-has="'admin:sysFinancialRecord:selectExport'" type="primary" @click="handlExport(2)"><icon-export /> 选择数据导出 </a-button>
            <!-- <a-button v-has="'admin:sysFamilyList:remove'" type="primary"  @click="handlExport(1)"><icon-export /> 当前搜索全部导出</a-button>  -->
            <a-button v-has="'admin:sysFinancialRecord:allExport'" type="primary"  @click="handlExport(3)"><icon-export /> 全部导出</a-button> 
          </a-space>
        </div>
        <a-row :gutter="24" >

          <a-col :span="24">
            <a-form-item field="idCard" :hide-label="true" >
               <!-- table -->
    <a-table :columns="columns" :data="tableData" 
     :scroll="{ x:1500 }"
     style="width:100%"
      :row-selection="{ type: 'checkbox', showCheckedAll: true }"
      :pagination="{ 'show-total': true, 'show-jumper': true, 'show-page-size': true, total: pager.total, current: currentPage }"
      row-key="withdrawal_order_id" @selection-change="(selection) => {deleteData = selection;}"
      @page-change="handlePageChange" @page-size-change="handlepage_sizeChange">
      <template #doctor_id="{record,rowIndex}">
        <div>{{(rowIndex+1)+(pager.page-1)*pager.page_size}}</div>
      </template>
      <template #pay_channel="{record}">
          <div v-if="record.pay_channel==1">小程序支付</div>
          <div v-else-if="record.pay_channel==2">微信扫码</div>
          <div v-else-if="record.pay_channel==3">模拟支付</div>
      </template>
      <!-- 1:待支付 2:待分配 3:待接诊 4:已接诊 5:已完成 6:已结束 7:已取消） -->
      <template #inquiry_status="{record}">
          <div v-if="record.inquiry_status==1">待支付</div>
          <div v-else-if="record.inquiry_status==2">待分配</div>
          <div v-else-if="record.inquiry_status==3">待接诊</div>
          <div v-else-if="record.inquiry_status==4">已接诊</div>
          <div v-else-if="record.inquiry_status==5">已完成</div>
          <div v-else-if="record.inquiry_status==6">已结束</div>
          <div v-else-if="record.inquiry_status==7">已取消</div>
      </template>
      <template #doctor_amount="{ record }">
        {{(record.doctor_amount) }}元
      </template>
  
      <template #patient_name_mask="{ record }">
        <div class="ta-patient" :title="record.patient_name_mask">{{record.patient_name_mask}}({{record.patient_sex==1?'男，':'女，'}}{{record.patient_age}}岁)</div>
      </template>
      
      <template #inquiry_type="{ record }">
        {{ formatInquiryType(record.inquiry_type) }}
      </template>
      <template #pay_time="{ record }">
        {{ parseTime(record.pay_time) }}
      </template>
      <template #action="{ record }">
        <a-space>
          <a-button v-has="'admin:sysFinancialRecord:orderDetail'" type="text"
            @click="handleDetail(record)"><icon-book />详情</a-button>
          <!-- <a-button v-has="'admin:sysFamilyList:edit'" type="text" @click="handleUpdate(record)"><icon-edit />
            修改</a-button> -->
          <!-- <a-button v-has="'admin:sysFamilyList:remove'" type="text"
            @click="() => { deleteVisible = true; deleteData = [record.doctor_id];  }"><icon-delete /> 删除</a-button> -->
        </a-space>
      </template>
    </a-table>
            </a-form-item>
          </a-col>
        </a-row>
        <a-divider /> 
      </a-form>
      <div class="titlebox" >
        <div class="bar"></div>
        <div class="name">操作</div>
      </div>
      <a-row :gutter="24" style="margin-top: 35px;" >
        <a-col :span="24">
          <a-form-item field="" label="" no-style>
            <a-space >
              <a-button type="primary" @click="()=>{confirmVisible=true;okStatus=1}" v-if="modalForm.examine_status==1" v-has="'admin:sysFinancialRecord:pass'">确认账单</a-button>
              <a-button type="primary" @click="()=>{confirmVisible=true;okStatus=2}" v-if="modalForm.examine_status==2 && modalForm.payment_status==0" v-has="'admin:sysFinancialRecord:pay'">确认打款</a-button>
              <a-button type="primary" status="danger" @click="()=>{rejectVisible=true;}"  v-if="modalForm.examine_status==1" v-has="'admin:sysFinancialRecord:reject'">拒绝提现</a-button>
            </a-space>
          </a-form-item>
        </a-col>
      </a-row> 
    </a-modal>
    <inquiryDetailMoneyModal :modalVisible="recordVisible" :modalForm="modalFormData" @inquiryVisibleChange="()=>{recordVisible=false}"></inquiryDetailMoneyModal>
    <numberModal
      :okVisible="okVisible"
      :api="editIncome"
      :id="withdrawal_order_id"
      :max="modalForm.actual_withdrawal_amount"
      @closeChange="closeChange"
     
    ></numberModal>

    <a-modal v-model:visible="rejectVisible" :modal-style="{width:'420px'}"  @ok="handleConfirmReject"
      @cancel="closeReject" >
      <template #title>
        提示
      </template>
      <a-form :model="rejectform" :rules="rules" ref="rejectFormRef" size="medium" label-align="left" auto-label-width>
      <a-form-item field="examine_fail_reason" label="拒绝原因:" >
        <a-textarea v-model.trim="rejectform.examine_fail_reason" allow-clear placeholder="请输入拒绝原因"></a-textarea>
      </a-form-item>
    </a-form>
    <template #footer>
      <a-button @click="closeReject"><template #icon><icon-close /></template>取消</a-button>
      <a-button type="primary" @click="handleConfirmReject"><template #icon><icon-check /></template>确认</a-button>
    </template>

    </a-modal>
     <!-- 二次确认弹框 -->
    <a-modal v-model:visible="confirmVisible" :modal-style="{width:'320px'}" body-class="okmodal" @ok="handleSubmitConfirm"
      @cancel="()=>confirmVisible=false">
      <template #title>
        提示
      </template>
      <div v-if="okStatus==1">确定账单审核通过？</div>
      <div v-else-if="okStatus==2">确定打款？</div>
    </a-modal>
</template>
<script setup>
import {ref,toRefs,watch,reactive,getCurrentInstance} from 'vue';
import {decryptCard} from '@/api/doctor/list';
import {getOrder,editIncome,withdrawalStatus,confirmPay,exportRecordOrder} from "@/api/finance/record"
import { parseTime } from '@/utils/parseTime';
import {formatInquiryType} from "@/utils/format"
import {getOrderDetail,inquiryCase} from '@/api/order/list';
import { Message } from '@arco-design/web-vue';
import { downloadFile } from '@/utils/downloadFile';
const props = defineProps({
  // 是否显示
  modalVisible: {
    type: Boolean,
    default: false,
  },
  modalForm: {
    type: Object,
  },
});
const { proxy } = getCurrentInstance();
const deleteData=ref([]);
const confirmVisible=ref(false);
const okVisible=ref(false);
const withdrawal_order_id=ref('');
const currentPage = ref(1);
const pager = {
    total: 1,
    page: 1,
    page_size: 10,
  };
const emits = defineEmits(['familyVisibleChange','freshDetail']);
const {modalVisible,modalForm} = toRefs(props);
//切换小眼睛
  const showEye = ref(false);
  const id_card_num = ref('');
  watch(()=>props.modalForm.withdrawal_id,()=>{
    if(props.modalForm.withdrawal_id){
      withdrawal_order_id.value=props.modalForm.withdrawal_id;
      handleGetOrder({
        ...pager,
        withdrawal_id:props.modalForm.withdrawal_id
      })
    }else{
      withdrawal_order_id.value='';
    }
  })
  //解密身份证号码
  const handelDecryptCard = async (user_id,family_id) => {
    showEye.value = true;
    const { data, code, message } = await decryptCard({
      user_id,
      family_id
    });
    if (code == 200) {
      id_card_num.value = data;
    }
  };
 
   // Table Columns
   const columns = [
    { title: '编号', dataIndex: 'doctor_id', slotName: 'doctor_id', width: '90' },
    { title: '订单编号', dataIndex: 'inquiry_no',width:200 },
  { title: '医生姓名', dataIndex: 'doctor_name',width:100  },
  { title: '就诊人', dataIndex: 'patient_name_mask',slotName:'patient_name_mask',width:200},
  { title: '联系电话', dataIndex: 'patient_mobile_mask',width: 130  },
  { title: '医生收益', dataIndex: 'doctor_amount',slotName:'doctor_amount',width:100 },
  { title: '支付方式', dataIndex: 'pay_channel',slotName:  'pay_channel'},
  { title: '订单状态', dataIndex: 'inquiry_status', slotName:'inquiry_status' },
  { title: '支付时间', dataIndex: 'pay_time', slotName: 'pay_time',width:200 },
  { title: '操作', slotName: 'action',fixed: "right", width: 100  },
]
// Akiraka 20230210 关闭弹窗
const handleClose = () => {
  emits('familyVisibleChange', false);
};
const tableData=ref([]);
const handleGetOrder=(params={})=>{
  getOrder(params).then(res=>{
    if(res.code==200){
      let data=res.data; 
      console.log(data.data)
      tableData.value=data.data;
      Object.assign(pager, { total: data.total, page: data.page, page_size: data.page_size });
    }
  })
}
  /**
   * 分页改变
   * @param {Number} [page]
   */
   const handlePageChange = (page) => {
    pager.page = page;
    // 修改当前页码
    currentPage.value = page;
    handleGetOrder({ ...pager, withdrawal_id:withdrawal_order_id.value});
  };

  // 每页数据量
  const handlepage_sizeChange = (page_size) => {
    pager.page_size = page_size;
    handleGetOrder({ ...pager, withdrawal_id:withdrawal_order_id.value});
  };
const patientData=reactive({});
const modalFormData=reactive({});
const recordVisible=ref(false);
//获取订单详情
const handleDetail = async (record) => {
    recordVisible.value = true;
    Object.assign(patientData,{});
    const { code, data} = await getOrderDetail(record.order_inquiry_id
);

    if (code == 200) {
      Object.assign(modalFormData, data);
      if(data.order_inquiry_case && data.order_inquiry_case.inquiry_case_id){
        const caseInfo= await inquiryCase(data.order_inquiry_case.inquiry_case_id);
        Object.assign(patientData,caseInfo.data);

      }
    }
  };

//关闭确认框
const closeChange = () => {
  okVisible.value = false;
  emits('freshDetail');
};
const rejectVisible=ref(false);
const rules = {
  examine_fail_reason:  [{ required: true, message: '请输入拒绝理由' }]
};
const rejectform=reactive({
  examine_fail_reason:''
})
//修改审核状态
const handleWithdrawalStatus= async(examine_status)=>{
  let obj=null;
  if(examine_status==2){
    obj={
      examine_status
    }
  }else{
    obj={
      examine_status,
      examine_fail_reason:rejectform.examine_fail_reason
    }
  }
 const {data,code}=await withdrawalStatus(withdrawal_order_id.value,obj);
  if(code==200){
    examine_status==2?Message.success("已通过审核"):Message.success("已拒绝成功")
    emits('freshDetail');
  }
  if(examine_status==3){
    closeReject()
  }
}
const okStatus=ref(1);
const handleConfirmReject=()=>{
  proxy.$refs.rejectFormRef.validate(async(valid) => {
    if (!valid) {
      handleWithdrawalStatus(3);
    }
  })
};
const closeReject=()=>{
  rejectVisible.value=false;
  proxy.$refs.rejectFormRef.resetFields();
}
const handleConfirmPay=async()=>{
  const {data,code}=await confirmPay(withdrawal_order_id.value);
  if(code==200){
    Message.success("打款成功");
  }
  emits('freshDetail');
};
const handleSubmitConfirm=()=>{
 if(okStatus.value==1){
   handleWithdrawalStatus(2);
 }else{
  handleConfirmPay();
 }
 
}
const handlExport=async(type)=>{
  proxy.$loading.show();
  let fromData=null;
  if(type==1){
    fromData={
      type,
      withdrawal_id:props.modalForm.withdrawal_id,
      ...queryForm
    }
  }else if(type==2){
      if(deleteData.value.length==0){
        proxy.$message.warning('请勾选数据');
        proxy.$loading.hide();
        return false;
      };
    let id='';
    deleteData.value.forEach((item)=>{
      if(id){
        id+=","+item
      }else{
        id=item;
      }
    })
    fromData={
      withdrawal_id:props.modalForm.withdrawal_id,
      type,
     id
    }
  }else if(type==3){
    //tableRef.value.selectAll(false)
    fromData={
      withdrawal_id:props.modalForm.withdrawal_id,
      type
    }
  }
  const {code,data}=await exportRecordOrder(fromData);
 if(code==200){
  downloadFile(data,'提现记录关联订单');
 }
  proxy.$loading.hide();
}
</script>
<style scoped>
  .cardNum {
    width: 150px;
  }
 .arco-form-item-layout-horizontal:first-child,
  .arco-form-item-layout-horizontal:nth-child(2) {
    align-items: center;
  }
  .cellbox{
    margin-top: 35px;
  }
  .cellbox .cell{
    width:50%;
    border-bottom:1px dashed #efefef;
    margin-bottom: 20px;
  }
  .cellbox .cell:first-child{
    border: none;
  }
 
  .box {
    display: flex;
    align-items: center;
  }

  .cert .arco-form-item-label-col {
    flex: 0 0 8px !important;
  }
  .arco-btn-disabled{
    cursor: not-allowed!important;
  }
</style>