<template>
  <div class="app-container">
    <a-form :model="queryForm" ref="queryFormRef" layout="inline">

      <a-form-item field="user_name" label="患者名字">
        <a-input :style="{ width: '182px' }" v-model="queryForm.user_name" placeholder="请输入患者名字" @press-enter="handleQuery" />
      </a-form-item>
      <a-form-item field="mobile" label="电话号码">
        <a-input :style="{ width: '182px' }" v-model="queryForm.mobile" placeholder="请输入电话号码" @press-enter="handleQuery" />
      </a-form-item>
      <a-form-item field="create_range_time" label="创建时间范围">
        <a-range-picker
          style="width: 260px"
          v-model="queryForm.create_range_time"
        />
      </a-form-item>
      <a-form-item>
        <a-space>
          <a-button type="primary" @click="handleQuery"><icon-search /> 搜索</a-button>
          <a-button @click="handleResetQuery"><icon-loop /> 重置</a-button>
        </a-space>
      </a-form-item>
    </a-form>

    <a-divider />

    <!-- action -->
    <div class="action">
      <a-space>
        <a-button v-has="'admin:sysPatientList:add'" type="primary" @click="handleAdd"><icon-plus /> 新增 </a-button>
        <!-- <a-button v-has="'admin:sysPatientList:remove'" type="primary" status="danger"><icon-delete /> 批量删除 </a-button> -->
      </a-space>
    </div>

    <!-- table -->
    <a-table :columns="columns" :data="tableData" 
      :row-selection="{ type: 'checkbox', showCheckedAll: true }"
      :pagination="{ 'show-total': true, 'show-jumper': true, 'show-page-size': true, total: pager.total, current: currentPage }"
      row-key="doctor_id" @selection-change="(selection) => {deleteData = selection;console.log(selection)}"
      @page-change="handlePageChange" @page-size-change="handlepage_sizeChange">
      <template #doctor_id="{record,rowIndex}">
        <div>{{(rowIndex+1)+(pager.page-1)*10}}</div>
      </template>
      <template #status="{ record }">
        <!-- 状态（0:禁用 1:正常 2:删除） -->
        <a-tag v-if="record.status == 0" color="#ffb400">禁用</a-tag>
        <a-tag v-else-if="record.status == 1" color="green">正常</a-tag>
        <a-tag v-else-if="record.status == 2" color="red" >删除</a-tag> 
        <!-- <a-switch @click="handleChangeStatus(record)" v-model="record.status"  :loading="loading"  :disabled="loading"  :checked-value="1" :unchecked-value="0" v-else/> -->
      </template>
      <template #is_platform_deep_cooperation="{ record }">
        <a-tag v-if="record.is_platform_deep_cooperation == 0" color="gray">否</a-tag>
        <a-tag v-else color="green">是</a-tag>
      </template>
  
      <template #disable_reason="{record}">
        <div class="reason" v-if="record.disable_reason" :title="record.disable_reason">{{ record.disable_reason }}</div>
        <div v-else>-</div>
      </template>
      <template #patient_family_count="{record}">
        <div>绑定了{{ record.patient_family_count}}个</div>
       
      </template>
      <template #action="{ record }">
        <a-space>
          <a-button v-has="'admin:sysPatientList:detail'" type="text"
            @click="handleDetail(record)"><icon-book />详情</a-button>
          
        </a-space>
      </template>
    </a-table>

    <!-- Modal -->
    <a-modal v-model:visible="modalVisible" fullscreen :title="modalTitle" title-align="start" :footer="false"
       @close="() => {$refs.modalFormRef.resetFields(); modalForm.patient_id = null;}">
      <div class="titlebox">
        <div class="bar"></div>
        <div class="name">用户信息</div>
      </div>
      <a-form :model="modalForm" :disabled="modalSatus=='detail' || modalForm.iden_auth_status==2
      "  ref="modalFormRef" :auto-label-width="true">
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item field="avatar" label="用户头像：">
              <a-space size="large">
                <a-image width="80" height="80" class="headImg" :src="modalForm.avatar">
                </a-image>
              </a-space>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item field="user_name" label="用户姓名：">
              <span>{{modalForm.user_name}}</span>
            </a-form-item>
          </a-col>
          <a-col :span="12">
     
            <a-form-item field="idCard" label="用户手机号：">
              <div class="box">
                <div class="cardNum">{{modalForm.mobile}}</div>
                <!-- <icon-eye-invisible class="eye" @click="handelDecryptCard(modalForm.user_id)" /> -->
              </div>
              <!-- <div class="box" v-show="showEye && modalSatus!='add'">
                <div class="cardNum">{{id_card_num}}</div>
                <icon-eye class="eye" @click="()=>{showEye=false}" />
              </div> -->
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item field="status" label="用户状态：">
              <!-- 0:禁用 1:正常 2:删除 -->
             <span v-if="modalForm.status==0">禁用</span>
             <span v-else-if="modalForm.status==1">正常</span>
             <span v-else-if="modalForm.status==2">删除</span>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="multi_point_status" label="注册时间：">
              <span v-if="parseTime(modalForm.created_at)">{{modalForm.created_at}}</span>
              <span v-else>-</span>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24" v-if="modalForm.disable_reason">
          <a-col :span="24">
            <a-form-item field="hospital_id" label="禁用理由：">
              <a-space size="large">
                <span >{{modalForm.disable_reason}}</span>
              </a-space>
            </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">
            <tableUnit  :pagination="false" :columns="family_columns" :data="family_data" @handleFamilyDetail="handleFamilyDetail"></tableUnit>
          </a-col>
         
        </a-row>
        <a-divider />
        <div class="titlebox" v-if="modalForm.user_ship_address && modalForm.user_ship_address.length>0">
          <div class="bar"></div>
          <div class="name">收货地址</div>
        </div>
        <div class="cellbox" v-if="modalForm.user_ship_address && modalForm.user_ship_address.length>0">
          <div class="cell" v-for="item in modalForm.user_ship_address">
          <a-row :gutter="24" >
          <a-col :span="12">
            <a-form-item field="" label="收货人姓名：">
                 {{ item.consignee_name}}
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="" label="收货人电话：">
              {{ item.consignee_tel}}
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24" >
          <a-col :span="24">
            <a-form-item field="" label="收货人地址：">
              {{ item.province}} {{item.city}}{{item.county}}{{item.address}}
            </a-form-item>
          </a-col>
        </a-row>
        </div>
        </div>
        <a-divider v-if="modalForm.user_ship_address && modalForm.user_ship_address.length>0"/>
      </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" v-has="'admin:sysPatientList:disable'" status="danger" @click="handleChangeStatus('0')" v-if="modalForm.status==1">禁用</a-button>
              <!-- <a-button type="primary" status="success" @click="handleChangeStatus('1')" v-if="modalForm.status==0">启用</a-button> -->
            </a-space>
            <!-- <a-space v-if="modalSatus=='edit'">
              <a-button type="primary" status="warning">拉黑</a-button>
              <a-button type="primary" status="danger">删除</a-button>
            </a-space> -->
          </a-form-item>
        </a-col>
      </a-row>
    </a-modal>


     <!-- 就诊人详情 -->
    <familyModal :modalVisible="familyVisible" :modalForm="familyForm" @familyVisibleChange="()=>{familyVisible=false}"></familyModal>
    <!-- Akiraka 20230223 删除与批量删除 结束 -->
    <a-modal v-model:visible="okVisible" :modal-style="{width:'420px'}" body-class="okmodal" 
      @cancel="cancelOk" @ok="handleOk">
      <template #title>
        提示
      </template>
      <a-form :model="okForm" :rules="formRules" ref="okModalFormRef" size="medium" label-align="left" auto-label-width>
      <a-form-item field="disable_reason" label="禁用理由" >
        <a-textarea v-model.trim="okForm.disable_reason" allow-clear placeholder="请输入取消订单理由"></a-textarea>
      </a-form-item>
      <!-- <template #footer>
      <a-button @click="()=>okVisible=false"><template #icon><icon-close /></template>取消</a-button>
      <a-button type="primary" @click="handleOk"><template #icon><icon-check /></template>确认</a-button>
    </template> -->
    </a-form>
    </a-modal>
  </div>
</template>

<script setup>
  import { reactive, ref, getCurrentInstance, onMounted, nextTick, watch, computed } from 'vue';
  import { getPatientList,getPatientDetail,changeStatus} from '@/api/patient/list';
  import {getFamilyDetail} from '@/api/patient/family';
  import {parseTime} from "@/utils/parseTime"
  // Akiraka 20230210 删除数据
  const deleteData = ref([])
  // Akiraka 20230210 删除对话框
  const deleteVisible = ref(false)
  // Akiraka 20230210 监听删除事件
  const loading=ref(true);
  const okVisible = ref(false);
  const okForm = reactive({
    disable_reason: ''
    });
const formRules = reactive({
  disable_reason:  [{ required: true, message: '请输入禁用理由' }]
});
  watch(() => deleteVisible.value, (value) => {
    if (value == false) {
      getPatientInfo(pager);
    }
  });

  const file = ref();
  const { proxy } = getCurrentInstance();
  const currentPage = ref(1);
  const family_data=ref([]);
  const family_columns=ref([{
    title: '编号',
    dataIndex: 'code',
    slotName:'code'
  },{
    title: '就诊人姓名',
    dataIndex: 'card_name_mask',
  },{
    title: '身份证号',
    dataIndex: 'id_number_mask',
  },{
    title: '与账号关系',
    dataIndex: 'relation',
    slotName:'relation'
  },{
    title: '添加时间',
    dataIndex: 'created_at',
    slotName:'created_at'
  }, { title: '操作', slotName: 'action'}])
  // Pager
  const pager = {
    total: 0,
    page: 1,
    page_size: 10,
  };
  // form
  const queryForm = reactive({

  });
  const modalForm = reactive({
    avatar: 'https://img.applets.igandanyiyuan.com/basic/file/patient_avatar.png',
 
  });
  watch(() => queryForm.create_range_time,
  (value) => {
    if (value) {
      let [startTime, endTime] = value;
      queryForm.created_at = startTime + '&' + endTime;
    } else {
      queryForm.created_at = '';
    }
  }
);
  // Modal
  const modalVisible = ref(false);
  const modalTitle = ref('默认标题');
 
  // Batch Del List
  let batchList = [];

  // Table Columns
  const columns = [
    { title: '编号', dataIndex: 'doctor_id', slotName: 'doctor_id', width: '90' },
    { title: '患者名字', dataIndex: 'user_name' },
    { title: '联系号码', dataIndex: 'mobile', width: 125 },
    { title: '就诊人', dataIndex: 'patient_family_count', slotName: 'patient_family_count' },
    { title: '注册时间', dataIndex: 'created_at', slotName: 'created_at' },
    { title: '启用状态', dataIndex: 'status', slotName: 'status' },
    { title: '禁用理由', dataIndex: 'disable_reason', slotName: 'disable_reason' },
    { title: '操作', slotName: 'action', fixed: "right", width: 120 },
  ];

  // Table Data
  const tableData = ref([]);
  //弹框状态
  const modalSatus = ref('add');

  // 新增Satus
  const handleAdd = () => {
    modalVisible.value = true;
    modalTitle.value = '新增患者';
    modalSatus.value = 'add';
    modalForm.patient_id = null;
  };

  //详情
  const handleDetail = async (record) => {
    modalVisible.value = true;
    modalTitle.value = '患者详情';
    modalSatus.value = 'detail';
    const { code, data, message } = await getPatientDetail(record.patient_id);

    if (code == 200) {
        Object.assign(modalForm, data);
        family_data.value=data.patient_family;
      }
    };

  const cur_parent_id=ref('');
  const switchStatus= async(patient_id,putData)=>{
    const {code,message}= await changeStatus(patient_id,putData);
     if(code==200){
      putData.status==0?proxy.$notification.success("禁用成功"):proxy.$notification.success('启用成功');
      modalVisible.value=false;
      handleQuery();
      proxy.$refs.okModalFormRef.resetFields();
     }else{
      proxy.$notification.error(message);
     }
  };
  const cancelOk=()=>{
    okVisible.value=false;
  }
  const handleOk = () => {
    proxy.$refs.okModalFormRef.validate(async(valid) => {
      if (!valid) {
        switchStatus(cur_parent_id.value,{
          status:0,
          disable_reason:okForm.disable_reason
        })
      }else{
        okVisible.value=true
      }
  })
}
 //改变用户状态
const handleChangeStatus=async(status)=>{
  if(status==0){
    cur_parent_id.value=modalForm.patient_id;
    okVisible.value=true;
  }
 
  // if(record.status==0){
  //   okVisible.value=true;
  // }else{
  //   switchStatus(record.patient_id,{
  //     status:1
  //   })
  }
     //就诊人详情
  const familyVisible=ref(false);
  const familyForm=reactive({
    user:{},
    avatar: 'https://img.applets.igandanyiyuan.com/basic/file/patient_avatar.png',
  });
  const handleFamilyDetail = async (family_id) => {
   const { code, data} = await getFamilyDetail(family_id);
   if (code == 200) {
       Object.assign(familyForm, data);
       familyVisible.value = true;
     }
   };


  /**
   * 分页改变
   * @param {Number} [page]
   */
  const handlePageChange = (page) => {
    pager.page = page;

    // 修改当前页码
    currentPage.value = page;
    getPatientInfo({ ...pager, ...queryForm });
  };

  // 每页数据量
  const handlepage_sizeChange = (page_size) => {
    pager.page_size = page_size;
    getPatientInfo({ ...pager, ...queryForm });
  };

  // 获取患者信息
  const getPatientInfo = async (params = {}) => {
    loading.value=true;
    const { data, code, message } = await getPatientList(params);
    if (code == 200) {
      tableData.value = data.data;
      Object.assign(pager, { total: data.total, page: data.page, page_size: data.page_size });
    }
     loading.value=false;
  };

  // 查询患者信息
  const handleQuery = async () => {
    pager.page = 1;
    const params = {
      page: pager.page,
      page_size: pager.page_size,
      ...queryForm,
    };

    getPatientInfo(params);
  };

  // 重置搜索
  const handleResetQuery = () => {
    proxy.$refs.queryFormRef.resetFields();
    getPatientInfo(queryForm);
  }
  
  
  onMounted(() => {
    getPatientInfo(pager);
  });
</script>

<style lang="scss" scoped>
  .action {
    margin-bottom: 12px;
  }

  .okmodal div {
    text-align: center;
  }

  .hospital_name {
    width: 140px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .headImg {
    margin-right: 20px;
    border-radius: 50%;
    width: 80px;
    height: 80px;
  }

  .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;
  }
  .cell{
    .arco-form-item{
      margin-bottom: 10px;
    }
  }
  .box {
    display: flex;
    align-items: center;
  }

  .cert .arco-form-item-label-col {
    flex: 0 0 8px !important;
  }

  .red {
    display: inline-block;
    margin-right: 5px;
    font-size: 14px;
    color: red;
    margin-top: 5px;
  }

  .cardNum {
    width: 148px;
  }
  .codbox{
    display: flex;
    align-items: center;
  }
  .reason{
    max-width:250px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
</style>