<template>
  <div class="white_bg burt-container">
    <a-form-model ref="form" layout="vertical" :model="form">
      <a-row :gutter="30">
        <a-col :lg="6" :sm="12">
          <a-form-model-item label="病历号">
            <a-select show-search v-model="form.mrnNo" :disabled="!!id"
              placeholder="病历号"  :filter-option="false"
              @search="getPatienList"
              @change="patienListChange">
              <a-select-option v-for="item in patientList" :key="item.id" :value="item.mrnNo">{{item.patientName}}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :lg="6" :sm="12">
          <a-form-model-item label="客户姓名">
            <a-input v-model="form.patientName" placeholder="请输入客户姓名" allow-clear :disabled="!!id"/>
          </a-form-model-item>
        </a-col>
        <a-col :lg="6" :sm="12">
          <a-form-model-item label="出生日期">
            <a-date-picker allow-clear :disabled="!!id"
              v-model="form.firstEnrollmentTime" placeholder="请选择出生日期" value-format="YYYY-MM-DD 00:00:00" />
          </a-form-model-item>
        </a-col>
        <a-col :lg="6" :sm="12">
          <a-form-model-item label="保险公司">
            <a-select v-model="form.payorCode" placeholder="请选择保险公司" :disabled="!!id"
              @change="_getPatientPolicyList">
              <a-select-option v-for="item in companyOptions" :key="item.id" :value="item.payorCode">
                {{ item.longName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :lg="6" :sm="12">
          <a-form-model-item label="保单号码">
            <a-select v-model="form.policyNo" placeholder="请选择保单号码" allowClear :disabled="!!id">
              <a-select-option v-for="item in PolicyOptions" :key="item.id" :value="item.policyNo">
                {{ item.policyNo }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :lg="6" :sm="12">
          <a-form-model-item label="主治医生">
            <a-select v-model="form.doctorCode" placeholder="请选择主治医生" :disabled="!!id"
              showSearch :filter-option="filterOption" optionFilterProp="label">
              <a-select-option v-for="item in doctorOptions" :key="item.doctorCode" :value="item.doctorCode"
                :label="item.doctorDesc+item.doctorCode">
                {{ item.doctorDesc }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :lg="6" :sm="12">
          <a-form-model-item label="预授权项目">
            <a-select v-model="form.authProject" placeholder="请选择预授权项目" allowClear :disabled="!!id">
              <a-select-option v-for="(item) in ProjectList" :key="item.id" :value="item.refcd">{{item.descCh}}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :lg="6" :sm="12">
          <a-form-model-item label="预计治疗时间">
            <a-date-picker allow-clear v-model="form.authorDate" placeholder="请选择预计治疗时间" :disabled="!!id"
              value-format="YYYY-MM-DD 00:00:00" />
          </a-form-model-item>
        </a-col>
        <a-col :lg="6" :sm="12">
          <a-form-model-item label="预计治疗费用">
            <div class="flex input-div">
              <a-input v-model="form.authorAmount" placeholder="请输入费用" type="number" :min="0" :disabled="!!id" />
              <a-select v-model="form.authorAmountUnit" style="width:90px;" :disabled="!!id">
                <a-select-option v-for="(item) in MoneyUnitOptions" :key="item.value" :value="item.value">{{item.name}}</a-select-option>
              </a-select>
            </div>
          </a-form-model-item>
        </a-col>
        <a-col :lg="6" :sm="12">
          <a-form-model-item label="初诊日期">
            <a-date-picker allow-clear v-model="form.firstVisitDate" placeholder="请选择初诊日期" :disabled="!!id"
              value-format="YYYY-MM-DD 00:00:00" />
          </a-form-model-item>
        </a-col>
        <a-col :lg="6" :sm="12">
          <a-form-model-item label="治疗目的">
            <a-select v-model="form.purpose" placeholder="请选择治疗目的" :disabled="!!id">
              <a-select-option value="01">疾病</a-select-option>
              <a-select-option value="02">事故</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :lg="6" :sm="12">
          <a-form-model-item label="治疗方案">
            <a-select v-model="form.treatmentPlan" placeholder="请选择治疗方案" :disabled="!!id">
              <a-select-option v-for="(item,i) in treatmentPlanList" :key="i" :value="item.refcd">{{item.descCh}}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :lg="6" :sm="12">
          <a-form-model-item label="诊断">
            <a-input v-model="form.diagnosis" placeholder="请输入诊断" allow-clear :disabled="!!id"/>
          </a-form-model-item>
        </a-col>
        <a-col :lg="6" :sm="12">
          <a-form-model-item label="病历资料">
            <a-upload name="file" :multiple="false" :showUploadList="true" :disabled="!!id"
              :fileList="form.medicalRecord"
              :customRequest="(file)=>uploadFile(file, 1)"
              :beforeUpload="()=>beforeUpload(1)"
              :remove="(file)=>removeFile(file, 1)">
              <a-button type="primary"> <Icon name="ssiupload" :size="18" />上传病历 </a-button>
            </a-upload>
          </a-form-model-item>
        </a-col>
      </a-row>
      <!--费用明细-->
      <a-row>
        <FeeDetail :id="id" ref="feeDetail" :ProjectList="ProjectList" @authorizeItemVoListChange="authorizeItemVoListChange" />
      </a-row>
      <a-row :gutter="30" class="footer-body">
        <a-col :lg="6" :sm="12">
          <a-form-model-item label="申请状态">
            <a-select v-model="form.authorStatus" placeholder="请选择申请状态">
              <a-select-option v-for="(item) in ApplyStatusOptions" :key="item.value" :value="item.value">{{item.name}}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :lg="6" :sm="12">
          <a-form-model-item label="批准次数/金额">
            <a-input v-model="form.approvalAmount" placeholder="请输入批准次数/金额" allow-clear />
          </a-form-model-item>
        </a-col>
        <a-col :lg="6" :sm="12">
          <a-form-model-item label="拒绝原因">
            <a-select v-model="form.rejectReason" placeholder="请选择拒绝原因">
              <a-select-option v-for="(item,i) in rejectReason" :key="i" :value="item.refcd">{{item.descCh}}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :lg="6" :sm="12">
          <a-form-model-item label="补充材料">
            <a-upload name="file" :multiple="false" :showUploadList="true"
              :fileList="form.supplementalResult"
              :customRequest="(file)=>uploadFile(file, 2)"
              :beforeUpload="()=>beforeUpload(2)"
              :remove="(file)=>removeFile(file, 2)">
              <a-button type="primary"> <Icon name="ssiupload" :size="18" />上传材料</a-button>
            </a-upload>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :lg="24" :sm="12" class="none-label">
          <a-form-model-item label="button">
            <a-button type="primary" @click="saveEvt" :loading="loading">
              <Icon :name="id?'ssibaocun':'ssiadd'" :size="14" />{{id? '保存预授权': '新建预授权'}}
            </a-button>
            <a-button type="primary" class="mar-left10" v-if="id" :loading="loading2"
              @click="sendEmailEvt">
              <Icon name="ssiemail" :size="14" />邮件发送
            </a-button>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
  </div>
</template>

<script>
import {MoneyUnitOptions,ApplyStatusOptions} from '@/utils/utilsdictOptions';
import FeeDetail from './components/feeDetail.vue';
import debounce from 'lodash/debounce';
import moment from 'moment';
import { mapState } from "vuex"
export default{
  data(){
    this.lastFetchId = 0;
    this.getPatienList = debounce(this.getPatienList, 800);
    return{
      loading: false,
      loading2: false,
      MoneyUnitOptions,
      ApplyStatusOptions,
      id: '', //预授权id
      form: {
        mrnNo: '',
        patientId: '',
        payorCode: '',
        policyNo: '',
        firstEnrollmentTime: '',
        authorAmountUnit: '01',
        medicalRecord: [], //病历资料
        supplementalResult: [], //补充材料
        authorizeItemVoList: [], //预授权费用数据
      },
      fetching: false,
      patientList: [], //远程搜到的客户信息
      companyOptions: [],  //保险公司
      PolicyOptions: [],  //保单号码
      doctorOptions: [], //医生列表
      ProjectList: [], //预授权项目
      rejectReason: [], //拒绝原因
      treatmentPlanList: [], //治疗方案
    }
  },
  components: {
    FeeDetail,
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.common.userInfo
    })
  },
  created(){
    this.id = this.$route.query.id || "";
    this.getRefcdByRefgrp();
    this._getDoctorListNoPage();//获取看诊医生下拉选项
    if(this.id){
      this.getDetail();
    }
  },
  methods: {
    init(){
      this.form = {
        mrnNo: '',
        patientId: '',
        payorCode: '',
        policyNo: '',
        firstEnrollmentTime: '',
        authorAmountUnit: '01',
        medicalRecord: [], //病历资料
        supplementalResult: [], //补充材料
        authorizeItemVoList: [], //预授权费用数据
      }
    },
    filterOption(val, option){
      let item = option.componentOptions.propsData; //propsData里面可以可以拿到lebel和value的值
      return item.label.toLowerCase().indexOf(val.toLowerCase()) >= 0
    },
    //预授权费用数据变更
    authorizeItemVoListChange(data){
      this.form.authorizeItemVoList = data;
    },
    //获取预授权详情
    getDetail(){
      this.$apis.AUTHORIZEDETAIL({
        id: this.id
      })
      .then((res)=>{
        if (res.returnCode === "0000") {
          let content = res.content || {}
          this.form = {
            ...content,
            medicalRecord: (content.medicalRecord || []).map((item)=>{
              return {
                uid: item.id,
                name: item.fileName,
                status: 'done',
                url: item.fileUrl,
              }
            }), 
            supplementalResult: (content.supplementalResult || []).map((item)=>{
              return {
                uid: item.id,
                name: item.fileName,
                status: 'done',
                url: item.fileUrl,
              }
            }),
            authorizeItemVoList: content.authorizeItemVoList || [],
          };
          this.$refs.feeDetail.dataList = this.form.authorizeItemVoList;
          this._getCompanyOptions();
        }else{
          this.$message.success(res.returnMsg);
        }
      })
    },
    // 获取看诊医生下拉选项
    _getDoctorListNoPage(){
      this.$apis.GETDOCTORlISTNOPAGE({"providerId": this.userInfo.providerId}).then((res) => {
        if (res.returnCode === "0000") {
          this.doctorOptions = res.content || [];
        }else{
          this.$message.success(res.returnMsg);
        }
      });
    },
    getPatienList(value){
      this.lastFetchId += 1;
      this.fetching = true;
      const fetchId = this.lastFetchId;
      this.$apis.PATIENTLISTNOPAGE({
        mrnNo: value
      })
      .then((res)=>{
        if (fetchId !== this.lastFetchId) {
          return;
        }
        if(res.returnCode == '0000'){
          this.patientList = res.content || [];
        }
        this.fetching = false;
      })
    },
    patienListChange(){
      this.form.payorCode = "";
      this.form.policyNo = ""; 
      let itemObj = this.patientList.find((item)=>{
        return this.form.mrnNo == item.mrnNo;
      }) || {};
      this.form.patientId = itemObj.id;
      this.form.patientName = itemObj.patientName;
      this.form.firstEnrollmentTime = itemObj.firstEnrollmentTime? moment(itemObj.firstEnrollmentTime).format('YYYY-MM-DD 00:00:00'): '';
      this._getCompanyOptions()
    },
    // 获取保险公司下拉选项
    _getCompanyOptions() {
      this.$apis.PATIENTPAYORLIST({
        patientId: this.form.patientId
      }).then((res) => {
        this.companyOptions = res.content || [];
      });
    },
    // 获取保单号码下拉选项
    _getPatientPolicyList() {
      this.$apis.PATIENTPOLICYLIST({
        patientId: this.form.patientId,
        payorCode: this.form.payorId,
      }).then((res) => {
        this.PolicyOptions = res.content || [];
      });
    },
    // 获取码表
    getRefcdByRefgrp() {
      //预授权项目
      this.$apis.GETREFCDBYREFGRP({
        modid: "CI",
        refgrp: "AUTH_PROJECT"
      }).then((res) => {
        this.ProjectList = res.content || [];
      });
      //拒绝原因
      this.$apis.GETREFCDBYREFGRP({
        modid: "CI",
        refgrp: "REJECT_REASON"
      }).then((res) => {
        this.rejectReason = res.content || [];
      });
      //治疗方案
      this.$apis.GETREFCDBYREFGRP({
        modid: "CI",
        refgrp: "TREATMENT_PLAN"
      }).then((res) => {
        this.treatmentPlanList = res.content || [];
      });
    },
    //上传之前
    beforeUpload(type){
      let len = type==1? this.form.medicalRecord.length: this.form.supplementalResult.length;
      if(len >= 5){
        this.$message.warning('不能超过5个文件');
        return false;
      }
      return true;
    },
    /**删除文件
     * type  1:上传病历  2:补充材料
     * **/
    removeFile(file, type){
      if(type == 2){
        let index;
        this.form.supplementalResult.forEach((item, i) => {
          if (item.uid == file.uid) {
            index = i;
          }
        });
        this.form.supplementalResult.splice(index, 1);
      }else{
        let index;
        this.form.medicalRecord.forEach((item, i) => {
          if (item.uid == file.uid) {
            index = i;
          }
        });
        this.form.medicalRecord.splice(index, 1);
      }
      return true;
    },
    /**上传文件
     * type  1:上传病历  2:补充材料
     * **/
    uploadFile(fileData, type){
      let formData = new FormData();
      formData.append("file", fileData.file);
      this.$apis.UPLOADIMG(formData)
      .then((res)=>{
        fileData.onSuccess();
        let tmp =  {
          uid: Math.random()*10000,
          name: res.title,
          status: 'done',
          url: res.url,
        }
        if(type==2){
          this.form.supplementalResult.push(tmp);
        }else{
          this.form.medicalRecord.push(tmp);
        }
        this.$forceUpdate();
      })
    },
    //保存
    saveEvt(){
      this.loading = true;
      let api = this.id? 'AUTHORIZEUPDATE': 'AUTHORIZECREATE';
      this.$apis[api]({
        ...this.form,
        medicalRecord: this.form.medicalRecord.map((item)=>{
          return {
            fileName: item.name,
            fileUrl: item.url,
          }
        }),
        supplementalResult: this.form.supplementalResult.map((item)=>{
          return {
            fileName: item.name,
            fileUrl: item.url,
          }
        })
      })
      .then((res)=>{
        this.loading = false;
        if(res.returnCode == '0000'){
          this.$message.success('保存成功');
          if(!this.id){
            this.$refs.feeDetail.dataList = [];
            this.init();
          }
        }else{
          this.$message.warning(res.returnMsg);
        }
      })
    },
    //发送邮件
    sendEmailEvt(){
      this.loading2 = true;
      this.$apis.AUTHORIZESENDEMAIL({
        id: this.id
      })
      .then((res)=>{
        this.loading2 = false;
        if(res.returnCode == '0000'){
          this.$message.success('发送成功');
        }else{
          this.$message.warning(res.returnMsg);
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.footer-body{
  margin-top: 25px;
}
</style>