<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="service_count" label="总服务数：">
                <a-input-number
              v-model="modalForm.service_count"
              :style="{ width: '320px' }"
              placeholder="请输入总服务数"
              class="input-demo"
              :step="1" :precision="0"
              :min="1"
            />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="monthly_frequency" label="每月次数：">
                <a-input-number
               v-model="modalForm.monthly_frequency"
              :style="{ width: '320px' }"
              placeholder="请输入每月次数"
              class="input-demo"
              :step="1" :precision="0"
              :min="0"
            />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24" >
          <a-col :span="12">
            <a-form-item field="service_rate" label="服务费率(%)：">
                <a-input
              v-model="modalForm.service_rate"
            
              :style="{ width: '320px' }"
              placeholder="请选择服务费率"
              class="input-demo"
              :step="1" :precision="0"
              :min="1"
            />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="effective_days" label="服务有效天数：">
                <a-input
              v-model="modalForm.effective_days"
              :style="{ width: '320px' }"
              placeholder="请输入服务有效天数"
              class="input-demo"
              :step="1" :precision="0"
              :min="0"
            />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24" >
          <a-col :span="12">
            <a-form-item field="my_package_product" label="关联商品：" >
             <a-select multiple v-model="modalForm.my_package_product" placeholder="请选择关联商品"  allow-search
             :loading="loading"  @search="handleGetProduct" @change="changeProduct" >
              <a-option v-for="item in productList" :key="item.product_id" :value="item.product_id" :label="item.product_name">
                {{ item.product_name }}
              </a-option>
             </a-select>
          </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24" >
          <a-col :span="12">
            <a-form-item field="" label="修改关联商品信息：" >
                <a-table :columns="product_columns" :data="product_data" style="width:100%;" :pagination="false">
                    <template #discount_product_price="{ record }">
                       <a-input-number v-model="record.discount_product_price" :min="0"/>
                     </template>
                     <template #quantity="{ record }">
                       <a-input-number v-model="record.quantity" :step="1" :precision="0" :min="1"/>
                     </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="handleSubmit" v-has="'admin:sysHealthList:save'">保存</a-button>
              </a-space>
            </a-form-item>
          </a-col>
        </a-row> 
    </a-modal>
  </template>
  <script setup>
  import { ref,toRefs,watch,getCurrentInstance,reactive,defineExpose} from 'vue';
  import { addHealth,updateHealth} from '@/api/inquiry/service';
  import { parseTime } from '@/utils/parseTime';
  import {getProduct} from '@/api/coupon/list';
  const { proxy } = getCurrentInstance();
  const product_data=ref([]);
  const props = defineProps({
    // 是否显示
    modalVisible: {
      type: Boolean,
      default: false,
    },
    id:{
     type:String,
     default:''
    },
    modalForm:{
        type:Object,
        default:{} 
    }
  });

const title=ref('添加问诊配置');
const productList=ref([]);
const loading=ref(false);
let  initData=[];
const reset=()=>{
    product_data.value=[];
};
const handleGetProduct=async(name='',id='')=>{
  loading.value=true;
  const {code,data}=await getProduct({
    product_name:'',
    product_id:'',
    limit:100
  });
  if(code==200){
    productList.value=data;
  }
  loading.value=false;
}
  
  const {modalVisible,id,modalForm}=toRefs(props);
  const emits = defineEmits(['healthVisibleChange','freshList']);
  watch(()=>props.id,(newVal,oldValval)=>{
    handleGetProduct();
    if(props.id){
      title.value='修改健康包';
     
    }else{
      title.value='添加健康包';
    }
  },{immediate:true});

  //  watch(()=>props.modalForm,()=>{
  //     if(id.value){
  //        let product=modalForm.value.health_package_product;
  //      initData=modalForm.value.health_package_product;
  //      if(product && product.length>0){
  //        modalForm.value.my_package_product=product.map((item)=>item.product_id);
  //        product_data.value=product;
  //      }
  //     }
  //  },{immediate:true})


    const getData=()=>{
       let product=modalForm.value.health_package_product;
       initData=modalForm.value.health_package_product;
       if(product && product.length>0){
         modalForm.value.my_package_product=product.map((item)=>item.product_id);
         product_data.value=product;
       }
    }
    
  const changeProduct=(val)=>{
       product_data.value=[];
       let json={};
       let count=0;
       console.log(initData)
      for (let i = 0; i < val.length; i++) {
        if(initData.length>0){
            for (let j = 0; j < initData.length; j++) {
              count++;
            if (val[i]=== initData[j].product_id){
              if(!json[initData[j].product_id]){
                  json[initData[j].product_id]=count;
                  product_data.value.push({
                  product_id:initData[j].product_id,
                  product_name:initData[j].product_name,
                  quantity:initData[j].quantity,
                  discount_product_price:initData[j].discount_product_price
              }) 
              }
            }else{
               let arr=productList.value.filter((item)=>item.product_id==val[i]);
                    if(!json[arr[0].product_id]){
                      json[arr[0].product_id]=count;
                    product_data.value.push({
                    product_id:arr[0].product_id,
                    product_name:arr[0].product_name,
                    quantity:1,
                    discount_product_price:10
                }) 
                };
                
       
            }
         }
       
        }else{
            let arr=productList.value.filter((item)=>item.product_id==val[i]);
                product_data.value.push({
                product_id:arr[0].product_id,
                product_name:arr[0].product_name,
                quantity:1,
                discount_product_price:10
             }) 
        }
       
    }
  };
  







  // Akiraka 20230210 关闭弹窗
  const handleClose = () => {
    proxy.$refs.modalFormRefConfig.resetFields();
    reset();
    emits('healthVisibleChange', false);
  };
  
  const handleSubmit=()=>{
    proxy.$refs.modalFormRefConfig.validate(async (valid) => {
        let data=null;
        for (let i = 0; i < product_data.value.length; i++) {
          if(!product_data.value[i].quantity){
            proxy.$message.warning('商品数量不能为空');
            return false
          };
          if(!product_data.value[i].discount_product_price	){
            proxy.$message.warning('商品折后价格不能为空');
            return false
          };
          
        }
        let obj=Object.assign({},modalForm.value,{health_package_product:product_data.value});
       
        if (!valid) {
          if(props.id){
            data= await updateHealth(props.id,obj)
          }else{
            data= await addHealth(obj);
          }
          if(data.code==200){
            props.id?proxy.$message.success('修改成功'):proxy.$message.success('添加成功');
            //emits('freshList', '');
          }
          handleClose();
        }else {
          console.log(valid)
          proxy.$message.error('表单校验失败');
          //done(false);
        }
      });
  };
  const rules = {
    service_count: [{ required: true, message: '请输入总服务天数' }],
    monthly_frequency:[{ required: true, message: '请输入每月次数' }],
    effective_days: [{ required: true, message: '请输入服务有效天数' }],
    service_rate:[{ required: true, message: '请输入服务费率' }],
    my_package_product: {type: 'array',required: true,message:'请选择关联商品'}
   
  };
  const product_columns=[
  {
    title: '商品id',
    dataIndex: 'product_id',
  },
  {
    title: '商品名称',
    dataIndex: 'product_name',
  },
  {
    title: '商品数量',
    dataIndex: 'quantity',
    slotName: 'quantity'
  },
  {
    title: '商品打折后价格',
    dataIndex: 'discount_product_price',
    slotName: 'discount_product_price'
  }
  
]
  defineExpose({
    reset,
    getData
});
  </script>
  <style scoped>

  </style>