<template>
  <!-- Modal -->
  <a-modal
    v-model:visible="modalVisible"
    fullscreen
    :title="title"
    title-align="start"
    :footer="false"
    @cancel="handleClose"
  >
    
    <a-form :model="modalForm" ref="modalFormRefConfig" :auto-label-width="true" :rules="rules">
      <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="inquiry_type" :hide-label="true">
            <a-select
            :disabled="inquiry_config_id?true:false" 
              v-model="modalForm.inquiry_type"
              placeholder="请选择问诊类型"
              @change="changeType"
              :style="{ width: '320px' }"
            >
              <!-- 1:专家问诊 2:快速问诊 3:公益问诊 4:问诊购药 -->
              <a-option :value="1">专家问诊</a-option>
              <a-option :value="2">快速问诊</a-option>
              <a-option :value="3">公益问诊</a-option>
              <a-option :value="4">问诊购药</a-option>
            </a-select>
          </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="inquiry_type" :hide-label="true">
            <a-select
            :disabled="inquiry_config_id?true:false" 
              v-model="modalForm.inquiry_mode"
              placeholder="请选择问诊类型"
              @change="changeMode"
              :style="{ width: '320px' }"
            >
              <!-- 1:'图文',2:'视频', 3:'语音', 4:'电话',5:'会员',6:'疑难会诊',7:'附赠沟通',8:'健康包',9:'服务包' -->
              <a-option :value="1">图文问诊</a-option>
              <a-option :value="2">视频问诊</a-option>
              <a-option :value="3">语音问诊</a-option>
              <a-option :value="4">电话购药</a-option>
              <a-option :value="5">会员</a-option>
              <a-option :value="6">疑难会诊</a-option>
            </a-select>
          </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="doctor_id" :hide-label="true">
            <a-space direction="vertical" size="large">
            <a-select  :style="{width:'420px'}" allow-search placeholder="请输入医生姓名" :disabled="(inquiry_config_id || !modalForm.inquiry_type)?true:false" v-model="modalForm.doctor_id" allow-clear
              :loading="loading" @change="changeDoctor" @search="handleDoctorList" @click="isHasType">
              <a-option size="large" style="max-width:500px" v-for="item in doctorData" :key="item.hospital_id"
                :value="item.doctor_id" :label="item.user_name">
                <span v-if="item.doctor_title || item.hospital_name || item.department_custom_name" :title="item.user_name+'('+formatDoctorTitle(item.doctor_title)+'—'+item.hospital_name+'—'+item.department_custom_name+')'"> {{item.user_name+'('+formatDoctorTitle(item.doctor_title)+'—'+item.hospital_name+'—'+item.department_custom_name+')'}}</span>
                <span v-else :title="item.user_name"> {{item.user_name}}</span>
              </a-option>
            </a-select>
        </a-space>
          </a-form-item>
        </a-col>
      </a-row>

      
  
      <a-divider />
      <!-- <div class="typebox" v-if="toggleType">
      </div> -->
      <div class="typebox" v-if="!toggleType ">
        <div class="titlebox" v-if="is_platform_deep_cooperation==1">
          <div class="bar"></div>
          <div class="name">问诊日期</div>
        </div>
         <div class="timecon" v-if="is_platform_deep_cooperation==1">
          <div class="left">
          <a-row :gutter="24" style="margin-top: 35px;">
          <a-col :span="24">
            <el-config-provider :locale="locale">
              <a-form-item field="" label="问诊日期：" >
            <el-date-picker
            value-format="YYYY-MM-DD"
            :disabled-date="disabledDate"
            :style="{ width: '320px' }"
        v-model="inquiry_date"
        type="dates"
        placeholder="选择问诊日期（可多选）"
      />
    </a-form-item>
    </el-config-provider>
          </a-col>
        </a-row>
        <a-row :gutter="24" >
          <a-col :span="24">
              <a-form-item field="" label="问诊时间：" >
                <a-select
                v-model="inquiry_time"
               placeholder="请选择问诊时间"
               multiple
              :style="{ width: '320px' }"
              @change="changeTime"
            >
              <a-option :value="item.inquiry_time_id" v-for="item in system_inquiry_time">{{ item.start_time }}—{{item.end_time}}</a-option>
            </a-select>
    </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24" >
          <a-col :span="24">
              <a-form-item field="" label="" >
                <a-space>
                  <a-button type="primary"
             @click="addTime"><icon-check-circle /> 添加</a-button
          >
          <a-button @click="reset"><icon-loop /> 重置</a-button>
                </a-space>

    </a-form-item>

          </a-col>
          
        </a-row>
         </div>
         <div class="line"></div>
         <div class="right">
          <a-form-item field="doctor_inquiry_time" :hide-label="true" :rules="[{ required: true, message: '请选择问诊价格' }]">
               <div class="surebox">
               <div class="titlebox">
                <div class="title">已选问诊时间</div>
                <a-button style="margin-left: 20px;" @click="clearTime" type="primary">清空</a-button>
               </div>
              <div class="timebox">
                 <a-space wrap>
                  <a-tag color="green" class="tag" closable v-for="(item,index) in slect_all_date" :key="item" @close="closeTag(index)">{{item}}</a-tag>
                 </a-space>
              </div>
               </div>
            </a-form-item>
         </div>
         </div>
        
        <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="24">
          <a-form-item field="" label="" no-style>
            <a-space  direction="vertical" size="large">
              <div v-if="is_platform_deep_cooperation==1">是</div>
              <div v-else>否</div>
            </a-space>
          </a-form-item>
        </a-col>
      </a-row> 
      <a-divider /> 
      </div>
      <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="inquiry_price" :hide-label="true"  v-if="modalForm.inquiry_type!=3" :rules="[{ required: true, message: '请输入问诊价格' }]">
            <a-input-number
             :min="min"
             :max="max"
            :style="{width:'180px'}"
              v-model="modalForm.inquiry_price"
              placeholder="输入问诊价格"
              :disabled="modalForm.inquiry_type==2 || modalForm.inquiry_type==4"
             
              mode="button"
            />
          </a-form-item>
            <a-form-item field="inquiry_price" :hide-label="true"  :rules="[{ required:true, message: '请选择问诊价格' }]" v-if="modalForm.inquiry_type==3">
            <a-select
              v-model="modalForm.inquiry_price"
              placeholder="请选择问诊价格"
              :style="{ width: '320px' }"
            >
              <a-option :value="item" v-for="item in inquiry_price_list" :key="item">{{ item }}</a-option>
            </a-select>
           </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="24">
          <a-form-item field="work_num_day" :hide-label="true">
            <a-space  direction="vertical" size="large">
              <a-input-number mode="button" v-model="modalForm.work_num_day" :style="{width:'180px'}" placeholder="每日最大接诊量" class="input-demo" :min="0" :max="max_patient"/> 
            </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="24">
          <a-form-item field="" :hide-label="true" :rules="[{required:true,message:'请设置问诊状态'}]">
            <a-space  direction="vertical" size="large">
              <a-switch v-model="modalForm.is_enable"   :checked-value="1" :unchecked-value="0" />
            </a-space>
          </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="handleSubmit" v-has="'admin:sysDoctorconfigList:save'">保存</a-button>
            </a-space>
          </a-form-item>
        </a-col>
      </a-row> 
  </a-modal>
</template>
<script setup>
import { ref,toRef, toRefs,onMounted,watch,getCurrentInstance,reactive } from 'vue';
import { addInquiryconfig,getDoctorList,inquiryPriceAndTime,getInquiryconfigDetail,editInquiryconfig} from '@/api/inquiry/config';
import { formatDoctorTitle } from '@/utils/format';
import { parseTime } from '@/utils/parseTime';
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
const { proxy } = getCurrentInstance();
let multi_point_status='';
const props = defineProps({
  // 是否显示
  modalVisible: {
    type: Boolean,
    default: false,
  },
  inquiry_config_id:{
   type:String,
   default:''
  }
});
const is_platform_deep_cooperation=ref(null);

const loading = ref(false);
const title=ref('添加问诊配置');
const  modalForm=reactive({
  inquiry_mode:1,
  inquiry_price:null,
  doctor_inquiry_time:[],
  is_enable:1
});
const disabledDate=(time)=>{
  return time.getTime() < Date.now() - 8.64e7;
}
const locale=ref('');
const toggleType=ref(true);
const slect_all_date=ref([]);
const {modalVisible,inquiry_config_id}=toRefs(props);
const emits = defineEmits(['familyVisibleChange','freshList']);
 // Rules
const doctorData=ref([]);
const handleDetail=()=>{
  getInquiryconfigDetail({
    inquiry_config_id:inquiry_config_id.value,
    inquiry_type:modalForm.inquiry_type,
    inquiry_mode:modalForm.inquiry_mode,
    doctor_id:modalForm.doctor_id

  }).then(data=>{
    if(data.code==200){
      let result=data.data;
      Object.assign(modalForm,result);
      if (result.inquiry_type == 1 || result.inquiry_type  == 3) {
        toggleType.value = true;
      } else {
        toggleType.value = false;
      }
      if(result.doctor_inquiry_time){
       slect_all_date.value=result.doctor_inquiry_time.map(item=>{
          return parseTime(item.inquiry_date,'{y}-{m}-{d}')+" "+item.start_time+"—"+item.end_time

        })
      };
      handleInquiryPriceAndTime();
      is_platform_deep_cooperation.value=result.user_doctor.is_platform_deep_cooperation;
      handleDoctorList(result.user_doctor.user_name);

    }
  })
};

const handleDoctorList=(value)=>{
  loading.value=true;
  let formData=null;
  if(modalForm.inquiry_type==4){
      formData={
      user_name:value,
      idcard_status:1,
      iden_auth_status:1,
      is_bind_bank:1,
      multi_point_status: 1
    }
  }else{
    formData= {
    user_name:value,
    idcard_status:1,
    iden_auth_status:1,
    is_bind_bank:1,
  }
  }
  getDoctorList(formData).then(data=>{
    if(data.code=200){
      doctorData.value=data.data;
      if(!value){
        modalForm.doctor_id='';
      }
    }
    loading.value=false;
  })
};
watch(()=>props.inquiry_config_id,(newVal,oldValval)=>{
  if(newVal){
    title.value='修改医生问诊配置'
    handleDetail()
  }else{
    //handleDoctorList();
    title.value='添加医生问诊配置';
    toggleType.value=true;
    modalForm.inquiry_price=null
  }
},{immediate:true})

 let rules = reactive({
         doctor_id: [{ required: true, message: '请输入医生姓名' }],
         inquiry_type: [{ required: true, message: '请选择问诊类型' }],
         work_num_day: [{ required: true, message: '请输入每日接诊数量' }],
         inquiry_price: [{ required: true, message: '请输入问诊价格' }]
 })


const changeDoctor=(value)=>{
   let cur=doctorData.value.filter((item)=> item.doctor_id==value);
   if(cur && cur.length==1){
    is_platform_deep_cooperation.value=cur[0].is_platform_deep_cooperation
   }else{
    is_platform_deep_cooperation.value=0
   }
};


const reset=()=>{
 inquiry_date.value=[];
 inquiry_time.value=[];
};
let temp_date=[];
const addTime=()=>{
  let temp=[];
  if(inquiry_date.value.length==0){
    proxy.$message.warning('请选择问诊日期!');
    return false;
  }
  if(inquiry_time.value.length==0){
    proxy.$message.warning('请选择问诊时间!');
    return false;
  }
  let arr1=inquiry_date.value
  let arr2=select_time.value;
  for (let i = 0; i < arr1.length; i++) {
        for (let j = 0; j < arr2.length; j++) {
          temp.push(arr1[i]+" "+arr2[j]);
        }
  }
  temp_date=temp_date.concat(temp);
  slect_all_date.value=[...new Set(temp_date)];
  reset();
}
const clearTime=()=>{
  temp_date=[];
  slect_all_date.value=[];
}
watch(slect_all_date,(newVal,oldVal)=>{
  if(newVal.length>0){
    console.log(newVal.length)
    modalForm.doctor_inquiry_time=newVal.map((item)=>{
      const [inquiry_date,time]=item.split(' ');
       const [start_time,end_time]=time.split("—");
       return {inquiry_date,start_time,end_time}
    })
  }else{
    modalForm.doctor_inquiry_time=[] 
  }
},{deep:true})
//删除标签tag
const closeTag=(index)=>{
slect_all_date.value.splice(index,1);
}
locale.value=zhCn;
//最小价格
const min=ref(0);
const max=ref(1000000);
const max_patient=ref(1000000);
const system_inquiry_time=ref([]);
//问诊日期
const inquiry_date=ref([]);
//问诊时间
const inquiry_time=ref([]);
const select_time=ref([]);


const changeTime=(value)=>{
  select_time.value=[];
  let arr=system_inquiry_time.value;
  for (let i = 0; i < arr.length; i++) {
            for (let j = 0; j < value.length; j++) {
                if(arr[j].inquiry_time_id === value[i]){
                  select_time.value.push(arr[j].start_time+"—"+arr[j].end_time);
                }
        }
     };
};



const changeType=(value)=>{
  if(value==1 || value==3){
    toggleType.value=true
   }else{
    toggleType.value=false
   };
   doctorData.value=[];
   modalForm.doctor_id='';
   modalForm.doctor_inquiry_time=[];
   modalForm.inquiry_price=null;
   slect_all_date.value=[];
   //切换重新验证
    proxy.$refs.modalFormRefConfig.clearValidate();
   handleInquiryPriceAndTime()
}
const changeMode=(value)=>{
  handleInquiryPriceAndTime();
}
const inquiry_price_list=ref([]);
const handleInquiryPriceAndTime=()=>{
  inquiryPriceAndTime({
    inquiry_type:modalForm.inquiry_type,
    inquiry_mode:modalForm.inquiry_mode
  }).then(data=>{
    if(data.code=200){
      const result=data.data;
      if(modalForm.inquiry_type==1){
        min.value=Number(result.min_inquiry_price);
        max.value=Number(result.max_inquiry_price);
      }else if(modalForm.inquiry_type==3){
        inquiry_price_list.value=result.inquiry_price.split(",").map((item)=>{
           return Number(item)
         }).sort((a, b)=>{return a-b})
      }else{
        system_inquiry_time.value=result.system_inquiry_time;
        modalForm.inquiry_price=Number(result.inquiry_price);
      };
     
      //modalForm.work_num_day=result.max_work_num_day;
      max_patient.value=result.max_work_num_day;
      // rules = reactive(rules_obj);
    }
  })
}
//添加配置
const handleAddInquiryconfig = async () => {
  
};
// Akiraka 20230210 关闭弹窗
const handleClose = () => {
  proxy.$refs.modalFormRefConfig.resetFields();
  reset();
  emits('familyVisibleChange', false);
  

};
const isHasType=()=>{
   if(!modalForm.inquiry_type){
    proxy.$message.error('请先选择问诊类型');
   }
};
const handleSubmit=()=>{
  proxy.$refs.modalFormRefConfig.validate(async (valid) => {
      let data=null;
      if (!valid) {
        if(props.inquiry_config_id){
          data= await editInquiryconfig(modalForm,props.inquiry_config_id)
        }else{
          data= await addInquiryconfig(modalForm);
        }
        if(data.code==200){
          props.inquiry_config_id?proxy.$message.success('修改成功'):proxy.$message.success('添加成功');
          emits('freshList', '');
        }
        handleClose();
      }else {
        console.log(valid)
        proxy.$message.error('表单校验失败');
        //done(false);
      }
    });
};
// onMounted(()=>{
//   handleDoctorList()
// })
</script>
<style scoped>
.tag{
  margin-bottom: 10px;
}
.tag:last-child{
  margin-bottom: 0;
}
.cardNum {
  width: 150px;
}
.arco-form-item-layout-horizontal:first-child,
.arco-form-item-layout-horizontal:nth-child(2) {
  align-items: center;
}
.surebox{
  width:100%;
}
.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;
}
.timebox{
  min-height:200px;
  width:100%;
  margin-top: 20px;
  padding: 20px;
  border:1px solid  var(--color-neutral-3);
  border-radius: 8px;
}
.timecon{
  display: flex;
  width:100%;
  justify-content: space-between;
  align-items: center;
}
.left{
  width:400px
}

.right{
 
  flex:1;
}
.line{
  height: 240px;
  width:2px;
  margin:0 100px;
  background: var(--color-neutral-3);
}
</style>