<template>
  <div class="white_bg burt-container">
    <Goback title="EOB详情" />
    <!-- form -->
    <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 v-model="form.payorCode" placeholder="请选择保险公司" allowClear>
              <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="EOB日期">
            <a-date-picker format="YYYY年MM月DD日" v-model="form.eobDate" placeholder="选择日期" />
          </a-form-model-item>
        </a-col>
        <a-col :lg="6" :sm="12">
          <a-form-model-item label="EOB名称">
            <a-input v-model="form.eobName" placeholder="请输入EOB名称" />
          </a-form-model-item>
        </a-col>
        <a-col :lg="6" :sm="12">
          <a-form-model-item label="EOB金额(人民币)">
            <a-input type="number" v-model="form.eobAmountCny" placeholder="请输入金额"/>
          </a-form-model-item>
        </a-col>
        <a-col :lg="6" :sm="12">
          <a-form-model-item label="EOB金额(美元)">
            <a-input type="number" v-model="form.eobAmountUsd" placeholder="请输入金额"/>
          </a-form-model-item>
        </a-col>
        <a-col :lg="6" :sm="12">
          <a-form-model-item label="EOB状态">
            <a-select v-model="form.eobSts" placeholder="请选择">
              <a-select-option v-for="(item,i) in EOBStatusOptions" :key="i" :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.eobRemark" placeholder="请输入备注"/>
          </a-form-model-item>
        </a-col>
        <a-col :lg="6" :sm="12">
          <a-form-model-item label="EOB文件">
            <a-upload name="file" :multiple="false" :showUploadList="true"
              :fileList="form.eobFile"
              :customRequest="uploadEvt"
              :remove="removeFile">
              <a-button type="primary"> <Icon name="ssiupload" :size="18" />上传EOB文件 </a-button>
            </a-upload>
          </a-form-model-item>
        </a-col>
        <a-col :lg="24" :sm="24" class="none-label">
          <a-form-model-item label="button">
            <a-button class="mar-left10" type="primary" @click="addNewEvt">
              <Icon :name="eobNo?'ssibaocun':'ssiadd'" :size="14" />{{eobNo?'保存EOB':'新建EOB'}}
            </a-button>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="30">
        <a-col :md="24" class="none-label">
          <a-form-model-item label="button">
            <!-- <a-button class="mar-left10" type="primary" @click="handlerSearch">
              <Icon name="ssisearch_active" :size="14" />查询
            </a-button> -->
            <a-button type="primary" @click="exportEvt">
              <Icon name="ssidaochu" :size="14" />导出 
            </a-button>
            <a-button class="mar-left10" type="primary" @click="addNewBill">
              <Icon :name="isEditNewEob?'ssibaocun':'ssiadd'" :size="14" />{{isEditNewEob? '保存账单': '添加账单'}}</a-button>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
    <!-- table -->
    <a-table :columns="columns" :data-source="dataList" :scroll="{ x: true }" :pagination="false"
      :row-selection="isEditNewEob?{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }:null">
      <template slot="visitTimeStart" slot-scope="text, record">
        <span>{{record.visitTimeStart? moment(record.visitTimeStart).format('YYYY-MM-DD'):''}}</span> ~ 
        <span>{{record.visitTimeEnd? moment(record.visitTimeEnd).format('YYYY-MM-DD'):''}}</span>
      </template>
      <template slot="claimsStatus" slot-scope="text">
        <span>{{text | formatClaimsStatus}}</span>
      </template>
      <template slot="operation" slot-scope="text, record">
        <a-button type="link" @click.stop="editEvt(record)">修改</a-button>
        <!-- <a-button v-if="record.eobNo" type="link" class="danger" @click.stop="delRecord(index)">删除</a-button> -->
      </template>
    </a-table>
    <BurtPagination :pagination="pagination" @pageChange="getData" />

    <a-modal title="编辑" :visible="dialogShow" width="700px" :maskClosable="false"
      okText="确定" cancelText="取消"
      @ok="handleEditOK" @cancel="dialogShow = false">
      <a-form-model ref="editForm" :model="editFormObj" :rules="editRules">
        <a-row :gutter="30">
          <a-col :lg="12" :sm="24">
            <a-form-model-item label="理赔状态" prop="claimsStatus">
              <a-select v-model="editFormObj.claimsStatus" placeholder="请选择理赔状态" allowClear>
                <a-select-option v-for="(item,i) in ClaimsStatusOptions" :key="i" :value="item.value">{{item.name}}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :lg="12" :xs="24">
            <a-form-model-item label="账单回款金额" prop="paidAmountEob">
              <a-input v-model.trim="editFormObj.paidAmountEob" placeholder="账单回款金额" type="number" @change="moneyChange" />
            </a-form-model-item>
          </a-col>
          <a-col :lg="12" :xs="24">
            <a-form-model-item label="未赔付金额" prop="refuseAmountEob">
              <a-input v-model.trim="editFormObj.refuseAmountEob" placeholder="未赔付金额" type="number" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :lg="12" :xs="24">
            <a-form-model-item label="寄送备注" prop="sendRemark">
              <a-textarea v-model.trim="editFormObj.sendRemark" placeholder="寄送备注" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import Goback from "@/components/CUSTOMER/goback";
import BurtPagination from "@/components/CUSTOMER/pagation";
import moment from "moment";
import {ClaimsStatusOptions,EOBStatusOptions} from '@/utils/utilsdictOptions.js'
import mixins from "@/mixins";
const columns = [
  { title: "账单编号", dataIndex: "receiptNo", ellipsis: true, width: 100 },
  { title: "客户姓名", dataIndex: "patientName", ellipsis: true, width: 85 },
  { title: "保险公司", dataIndex: "payorName", ellipsis: true, width: 80 },
  { title: "就诊日期", dataIndex: "visitTimeStart", ellipsis: true, width: 110, scopedSlots: { customRender: "visitTimeStart" } },
  { title: "理赔状态", dataIndex: "claimsStatus", ellipsis: true, width: 90, scopedSlots: { customRender: "claimsStatus" } },
  { title: "账单金额", dataIndex: "receiptAmount", ellipsis: true, width: 85 },
  { title: "自付金额", dataIndex: "selfpaidAmount", ellipsis: true, width: 85 },
  { title: "理赔金额", dataIndex: "eobPaidAmount", ellipsis: true, width: 85 },
  { title: "回款金额", dataIndex: "paidAmountEob", ellipsis: true, width: 85 },
  { title: "未清金额", dataIndex: "refuseAmountEob", ellipsis: true, width: 85 },
  { title: "保险公司欠费", dataIndex: "payorNoPaidAmount", ellipsis: true, width: 110, },
  { title: "个人欠费", dataIndex: "perNoPaidAmount", ellipsis: true, width: 85 },
  { title: "备注", dataIndex: "sendRemark", ellipsis: true, width: 120 },
  { title: "操作", dataIndex: "operation", scopedSlots: { customRender: "operation" }, fixed: "right", width: "170px", align: "center"},
];
export default {
  data() {
    return {
      dialogShow: false,
      columns,
      ClaimsStatusOptions,
      EOBStatusOptions,
      eobNo: '', //eob编号
      form: {
        eobDate: '',
        payorCode: '',
        eobName: '',
        eobAmountCny: '',
        eobAmountUsd: '',
        eobSts: '',
        eobRemark: '',
        eobFile: []
      },
      dataList: [],
      isEditNewEob: false, //是否在新建EOB
      companyOptions: [], //保险公司
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      selectedRowKeys: [], // Check here to configure the default column
      editFormObj: {
        receiptNo: '',
        claimsStatus: '',
        paidAmountEob: '',
        refuseAmountEob: ''
      },
      editRules: {
        
      },
    };
  },
  mixins: [mixins],
  components: {
    Goback,
    BurtPagination,
  },
  created(){
    this.eobNo = this.$route.query.eobNo;
    this._getCompanyOptions();
    if(this.eobNo){
      let EobDataDetail = localStorage.getItem('EobDataDetail');
      let dataDetail = EobDataDetail? JSON.parse(EobDataDetail): {};
      if(dataDetail.eobFile){
        dataDetail.eobFile = [
          {
            uid: Math.random()*10000,
            name: dataDetail.eobFile.slice(dataDetail.eobFile.lastIndexOf('/')+1),
            status: 'done',
            url: dataDetail.eobFile,
          }
        ]
      }else{
        dataDetail.eobFile = [];
      }
      this.form = dataDetail;
      this.getData();
    }
  },
  methods: {
    moment,
    onSelectChange(selectedRowKeys) {
      let arr = [];
      for(let i=0; i<selectedRowKeys.length; i++){
        let idx = selectedRowKeys[i];
        if(this.dataList[idx].eobNo){
          this.$msg.destroy();
          this.$message.warning('EOB编号已存在')
        }else{
          arr.push(idx);
        }
      }
      this.selectedRowKeys = arr;
    },
    handlerSearch() {
      this.pagination.pageNum = 1;
      this.isEditNewEob = false;
      this.getData();
    },
    //回款金额改变
    moneyChange(){
      this.editFormObj.refuseAmountEob = this.form.eobPaidAmount||0 - this.editFormObj.paidAmountEob||0;
    },
    // 获取保险公司下拉选项
    _getCompanyOptions() {
      this.$apis.GETCOMPANYOPTIONS().then((res) => {
        this.companyOptions = res.content || [];
      });
    },
    getData() {
       this.$apis.QUERYEOBRECEIPTLIST({
        pageNum: this.pagination.pageNum,
        pageSize: this.pagination.pageSize,
        eobNo: this.eobNo
       })
      .then((res) => {
        if (res.returnCode == "0000") {
          let content = res.content || {};
          this.pagination.total = content.total || 0;
          this.dataList = content.list || [];
        } else {
          this.$message.error(res.returnMsg);
        }
      });
    },
    //修改单条数据
    editEvt(record) {
      this.dialogShow = true;
      this.$nextTick(()=>{
        this.editFormObj = {
          id: record.id,
          receiptNo: record.receiptNo,
          refuseAmountEob: record.refuseAmountEob || "",
          claimsStatus: record.claimsStatus || "",
          paidAmountEob: record.paidAmountEob || "",
        };
        this.moneyChange();
      })
    },
    //编辑保存
    handleEditOK() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$apis.SAVEEOBRECEIPTINFO({
            ...this.form,
            eobFile: this.form.eobFile.length>0? this.form.eobFile[0].url: '',
            eobReceiptList: [this.editFormObj],
            eobDate: this.form.eobDate?moment(this.form.eobDate).format('YYYY-MM-DD 00:00:00'):''
          })
          .then((res) => {
            if (res.returnCode == "0000") {
              this.$message.success("编辑成功");
              this.dialogShow = false;
              this.getData();
            } else {
              this.$message.error(res.returnMsg);
            }
          });
        }
      });
    },
    //删除记录
    delRecord(index) {
      this.$modal.confirm({
        title: "删除",
        content: "确定删除该条记录？",
        okText: "确认",
        cancelText: "取消",
        onOk: () => {
          this.$apis.DELEOBRECEIPTINFO({
            eobNo: this.dataList[index].eobNo,
          })
          .then((res) => {
            if (res.returnCode == "0000") {
              this.$message.success("删除成功");
              this.dataList.splice(index, 1);
            } else {
              this.$message.error(res.returnMsg);
            }
          });
        },
        onCancel: () => {},
      });
    },
    //导出
    exportEvt(){
      this.$apis.EOBRECEIPLISTEXPORT({
        eobNo: this.eobNo
      })
      .then(res => {
        let blob = new Blob([res.data], {
          type:"application/vnd.ms-excel;charset=utf-8"
        });
        let url=window.URL.createObjectURL(blob);
        let aLink=document.createElement("a");
        aLink.style.display="none";
        aLink.href=url;
        aLink.setAttribute("download","EOB关联账单.xls");
        document.body.appendChild(aLink);
        aLink.click();
        document.body.removeChild(aLink);
        window.URL.revokeObjectURL(url);
      }) 
    },
    //添加账单
    addNewBill(){
      this.isEditNewEob = !this.isEditNewEob;
      if(!this.isEditNewEob){ //保存
        this.addNewEvt()
        .then(()=>{
          this.isEditNewEob = false;
        })
      }else{ //查询所有未加入的账单
        this.pagination.pageNum = 1;
        this.$apis.QUERYEOBNEEDRECEIPTLIST({
          pageNum: this.pagination.pageNum,
          pageSize: this.pagination.pageSize
        })
        .then((res) => {
          if (res.returnCode == "0000") {
            this.selectedRowKeys = [];
            let content = res.content || {};
            this.pagination.total = content.total || 0;
            this.dataList = content.list || [];
          } else {
            this.$message.error(res.returnMsg);
          }
        });
      }
    },
    //新建/保存EOB
    addNewEvt(){
      let eobReceiptList = [];
      this.dataList.forEach((item,index)=>{
        if(this.selectedRowKeys.indexOf(index)!=-1){
          eobReceiptList.push({
            id: item.id,
            receiptNo: item.receiptNo,
            refuseAmountEob: item.refuseAmountEob,
            paidSts: item.paidSts,
            paidAmountEob: item.paidAmountEob,
          })
        }
      })
      let formData = {
        ...this.form,
        eobFile: this.form.eobFile.length>0? this.form.eobFile[0].url: '',
        eobReceiptList: eobReceiptList,
        eobDate: this.form.eobDate?moment(this.form.eobDate).format('YYYY-MM-DD 00:00:00'):'',
        eobNo: this.eobNo
      }
      return new Promise((resolve,reject)=>{
        this.$apis.SAVEEOBRECEIPTINFO(formData)
        .then((res) => {
          if (res.returnCode == "0000") {
            this.eobNo = res.content;
            this.$message.success("成功");
            this.selectedRowKeys = [];
            this.getData();
            resolve();
          } else {
            this.$message.error(res.returnMsg);
            reject();
          }
        });
      })
    },
    removeFile(){
      return new Promise((resolve)=>{
        this.form.eobFile = [];
        resolve();
      });
    },
    //上传
    uploadEvt(fileData){
      let formData = new FormData();
      formData.append("file", fileData.file);
      this.$apis.UPLOADIMG(formData)
      .then((res)=>{
        fileData.onSuccess();
        let fileList = [
          {
            uid: Math.random()*10000,
            name: res.title,
            status: 'done',
            url: res.url,
          }
        ]
        this.form.eobFile = fileList;
      })
    }
  },
};
</script>

<style lang="less" scoped>
.none-label {
  text-align: right;
  .ant-form-item-label {
    opacity: 0;
  }
}
.ant-btn .icon-class {
  .mg-r(10);
}
.success.ant-btn-link {
  color: #4cd964;
}
.danger.ant-btn-link {
  color: #ff3b30;
}
</style>
