<template>
  <!-- 收费查询-账单查询 -->
  <div class="white_bg burt-container custom-info">
    <Goback title="理赔件详情" />
    <!-- form -->
    <a-form-model ref="form" layout="vertical" :model="form">
      <a-row :gutter="30">
        <a-col :lg="8" :sm="12">
          <a-form-model-item label="保险公司">
            <a-select v-model="form.payorCode" placeholder="请选择保险公司" allow-clear :disabled="!isEdit">
              <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="8" :sm="12">
          <a-form-model-item label="寄送状态">
            <a-select v-model="form.sendSts" placeholder="请选择寄送状态" allow-clear :disabled="!isEdit">
              <a-select-option value="1">已寄送</a-select-option>
              <a-select-option value="2">未寄送</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :lg="8" :sm="12">
          <a-form-model-item label="快递公司">
            <a-select v-model="form.sendCompany" placeholder="请选择快递公司" showSearch allow-clear :disabled="!isEdit">
              <a-select-option v-for="(item) in expressList" :key="item.id" :value="item.descCh">{{item.descCh}}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :lg="8" :sm="12">
          <a-form-model-item label="快递单号">
            <a-input v-model="form.trackingNo" placeholder="请输入快递单号" allow-clear :disabled="!isEdit" />
          </a-form-model-item>
        </a-col>
        <a-col :lg="8" :sm="12">
          <a-form-model-item label="寄送方式">
            <a-select v-model="form.sendMode" placeholder="请选择寄送方式" allow-clear :disabled="!isEdit">
              <a-select-option value="快递">快递</a-select-option>
              <a-select-option value="邮件">邮件</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :lg="8" :sm="12">
          <a-form-model-item label="寄送日期">
            <a-date-picker format="YYYY年MM月DD日" v-model="form.sendDate" placeholder="选择日期" />
          </a-form-model-item>
        </a-col>
        <a-col :lg="8" :sm="12">
          <a-form-model-item label="寄送地址">
            <a-input v-model="form.sendAddress" placeholder="请输入寄送地址" allow-clear :disabled="!isEdit" />
          </a-form-model-item>
        </a-col>
        <a-col :lg="8" :sm="12">
          <a-form-model-item label="寄送邮箱">
            <a-input v-model="form.sendEmail" placeholder="请输入寄送邮箱" allow-clear :disabled="!isEdit" />
          </a-form-model-item>
        </a-col>
        <a-col :lg="8" :sm="12">
          <a-form-model-item label="寄送备注">
            <a-textarea v-model="form.sendRemark" placeholder="请输入寄送备注" :auto-size="{ minRows: 2, maxRows: 5 }" allow-clear :disabled="!isEdit" />
          </a-form-model-item>
        </a-col>
        <a-col :sm="24" class="none-label" v-if="isEdit">
          <div class="btn-div flex">
            <span></span>
            <a-form-model-item label="button">
              <a-button class="mar-left10" type="primary" @click="addNewCharge">
                <Icon :name="sendBatchNo?'ssibaocun':'ssiadd'" :size="14" />{{sendBatchNo?'保存寄送':'新建寄送'}}</a-button>
            </a-form-model-item>
          </div>
        </a-col>
      </a-row>
    </a-form-model>
    <a-form-model ref="form" layout="vertical" :model="searchForm">
        <a-row :gutter="30">
            <a-col :lg="8" :sm="12">
                <a-form-model-item label="就诊日期">
                    <a-range-picker format="YYYY-MM-DD" value-format="YYYY-MM-DD" v-model="searchForm.visitTimeStart" :placeholder="['选择就诊开始日期', '选择就诊结束日期']" />
                </a-form-model-item>
            </a-col>
            <a-col :lg="8" :sm="12">
                <a-form-model-item label="病历号">
                    <a-input v-model="searchForm.mrnNo" placeholder="请输入病历号" allow-clear />
                </a-form-model-item>
            </a-col>
            <a-col :lg="8" :sm="12">
                <a-form-model-item label="客户名称">
                    <a-input v-model="searchForm.patientName" placeholder="请输入客户名称" allow-clear />
                </a-form-model-item>
            </a-col>
        </a-row>
      <a-row :gutter="30">
        <a-col :sm="24" class="none-label">
          <div class="btn-div flex">
            <span></span>
            <a-form-model-item label="button">
              <a-button type="primary" @click="handlerSearch">
                <Icon name="ssisearch_active" :size="14" />查询
              </a-button>
              <a-button class="mar-left10" type="primary" @click="exportEvt">
                <Icon name="ssidaochu" :size="14" />导出 
              </a-button>
              <a-button class="mar-left10" type="primary" @click="addNewBill" v-if="isEdit">
                <Icon :name="isEditNewBill?'ssibaocun':'ssiadd'" :size="14" />{{isEditNewBill? '保存账单': '添加账单'}}</a-button>
            </a-form-model-item>
          </div>
        </a-col>
      </a-row>
    </a-form-model>

    <!-- table -->
    <a-table :columns="columns" :data-source="dataList" :scroll="{ x: true }" :pagination="false"
      :row-selection="isEditNewBill? { selectedRowKeys: selectedRowKeys, onChange: onSelectChange }: null">
      <template slot="sendDate" slot-scope="text">
        {{ text? moment(text).format('YYYY-MM-DD'): '' }}
      </template>
      <template slot="sendSts" slot-scope="text">
        {{ text==1?'已寄送':'未寄送' }}
      </template>
      <template slot="operation" slot-scope="text, record">
        <!-- <a-button type="link" @click.stop="editEvt(record)">修改</a-button> -->
        <a-button type="link" class="danger" @click.stop="delRecord(record)">删除</a-button>
      </template>
    </a-table>
    <!--分页-->
    <BurtPagination :pagination="pagination" @pageChange="getPageData" />

    <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" :xs="24">
            <a-form-model-item label="保险公司" prop="payorCode">
              <a-select v-model="editFormObj.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="12" :sm="24">
            <a-form-model-item label="寄送状态" prop="sendSts">
              <a-select v-model="editFormObj.sendSts" placeholder="请选择寄送状态" allowClear>
                <a-select-option :value="1">已寄送</a-select-option>
                <a-select-option :value="2">未寄送</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :lg="12" :sm="24">
            <a-form-model-item label="寄送日期" prop="sendDate">
              <a-date-picker format="YYYY年MM月DD日" v-model="editFormObj.sendDate" placeholder="选择日期" />
            </a-form-model-item>
          </a-col>
          <a-col :lg="12" :xs="24">
            <a-form-model-item label="快递单号" prop="trackingNo">
              <a-input v-model.trim="editFormObj.trackingNo" placeholder="快递单号" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="30">
          <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 { numValid } from "@/utils/index"

export default {
  data() {
    return {
      loading: false,
      dialogShow: false,
      isEdit: false,
      sendBatchNo: '', //寄送批号
      form: {
        payorCode: '',
        sendSts: '',
        sendMode: '',
        sendDate: '',
        sendCompany: '',
        trackingNo: '',
        sendAddress: '',
        sendEmail: '',
        sendRemark: ''
      },
      searchForm: {},
      searchData: {},
      companyOptions: [], //保险公司
      expressList: [], //快递列表
      selectedRowKeys: [], // Check here to configure the default column
      dataList: [],
      cacheDataList: {},
      isEditNewBill: false, //是否在新建账单
      pagination: {
        pageNum: 1,
        pageSize: 100,
        total: 0,
      },
      editFormObj: {
        payorCode: '',
        sendSts: '',
        sendDate: '',
        trackingNo: '',
        sendRemark: '',
      },
      editRules: {
        sendDate: [{ required: true, message: "请选择寄送日期", trigger: "change" }],
        trackingNo: [{ required: true, message: "请输入寄送单号", trigger: "blur" }],
      },
    };
  },
  components: {
    Goback,
    BurtPagination,
  },
  computed: {
    columns() {
        const base = [
            { title: "就诊日期", dataIndex: "receiptDate", width: 200,scopedSlots: { customRender: "receiptDate" } },
            { title: "病历号", dataIndex: "mrnNo", key:"mrnNo",align:'center', width: 136},
            { title: "客户姓名", dataIndex: "patientName", width: 98 },
            { title: "账单编号", dataIndex: "receiptNo", key:"receiptNo",align:'center', width: 136},
            { title: "保险公司", dataIndex: "payorName", width: 110 },
            { title: "应收金额", dataIndex: "chargeAmount", width: 100, align: 'center' },
            { title: "折扣金额", dataIndex: "discountAmount", width: 100, align: 'center' },
            { title: "减免金额", dataIndex: "discountAmount2", width: 100, align: 'center' },
            { title: "客户自付", dataIndex: "selfpaidAmount", width: 100, align: 'center', customRender: (val, row) => {
                return <a-input v-model={row.selfpaidAmount} allow-clear />
            } },
            { title: "理赔金额", dataIndex: "paidAmount", width: 100, align: 'center' },
        ];
        if(this.sendBatchNo && ! this.isEditNewBill && this.isEdit){ // 编辑状态下已经保存的数据才可进行操作
            return base.concat([
                { title: "操作", key: "operation", width: "100px",fixed: "right",scopedSlots: { customRender: "operation" }},
            ]);
        }
        return base

    }
  },
  created() {
    const { sendBatchNo, isEdit } = this.$route.query;
    this.sendBatchNo = sendBatchNo;
    this.isEdit = isEdit;
    this._getCompanyOptions();
    this.getRefcdByRefgrp();
    if(this.sendBatchNo){
      let jisongDataDetail = localStorage.getItem('jisongDataDetail');
      this.form = jisongDataDetail? JSON.parse(jisongDataDetail): {};
      this.getData();
    }
  },
  methods: {
    moment,
    onSelectChange(selectedRowKeys) {
      let arr = [];
      for(let i=0; i<selectedRowKeys.length; i++){
        let idx = selectedRowKeys[i];
        if(this.dataList[idx].sendBatchNo){
          this.$msg.destroy();
          this.$message.warning('寄送批号已存在')
        }else{
          arr.push(idx);
        }
      }
      this.selectedRowKeys = arr;
    },
    // 分页回调
    getPageData(pager) {
      if(pager){
        this.pagination = {
            ...this.pagination,
            ...pager
        }
      }
      if(this.isEditNewBill) { // 新增时添加了账单信息 那分页也应该是调账单信息接口
        this._getNewBillList()
      } else {
        this.getData()
      }
    },
    // 获取列表数据
    getData() {
      this.selectedRowKeys = [];
      let filter = {
        pageNum: this.pagination.pageNum,
        pageSize: this.pagination.pageSize,
        sendBatchNo: this.sendBatchNo || undefined,
        ...this.searchData
      }
      this.$apis.QUERYSENDRECEIPLIST(filter)
      .then((res) => {
        if (res.returnCode == "0000") {
          let content = res.content || {};
          this.pagination.total = content.total || 0;
          this.dataList = content.list || [];
          this.cacheDataList[filter.pageNum] = this.dataList
        } else {
          this.$message.error(res.returnMsg);
        }
      });
    },
    // 获取保险公司下拉选项
    _getCompanyOptions() {
      this.$apis.GETCOMPANYOPTIONS().then((res) => {
        this.companyOptions = res.content || [];
      });
    },
    // 获取快递列表
    getRefcdByRefgrp() {
      this.$apis.GETREFCDBYREFGRP({
        modid: "CI",
        refgrp: "SEND_COMPANY"
      }).then((res) => {
        this.expressList = res.content || [];
      });
    },
    //查看 
    detailEvt(record) {
      const { receiptNo } = record;
      this.$router.push({
        name: "chargeQueryDetail",
        query: { receiptNo },
      });
    },
    editEvt(record) {
      this.editFormObj = {
        ciReceiptSendVos: [
          {
            id: record.id,
            receiptNo: record.receiptNo,
          }
        ],
        payorCode: record.payorCode || "",
        sendSts: Number(record.sendSts) || "",
        sendDate: record.sendDate || "",
        trackingNo: record.trackingNo || "",
        sendRemark: record.sendRemark || "",
      };
      this.dialogShow = true;
    },
    //编辑保存
    handleEditOK() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$apis.SAVERECEIPSENDINFO({
            ...this.editFormObj,
            sendDate: moment(this.editFormObj.sendDate).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);
            }
          });
        }
      });
    },
    handlerSearch() {
      this.pagination.pageNum = 1;
      let visitTimeStart = this.searchForm.visitTimeStart || []
      this.searchData = this.$lodash.cloneDeep({
        ...this.searchForm,
        visitTimeEnd: visitTimeStart[1] ? visitTimeStart[1] + ' 23:59:59' : undefined,
        visitTimeStart: visitTimeStart[0] ? visitTimeStart[0] + ' 00:00:00' : undefined,
      });
      if(this.isEditNewBill) { // 新增时添加了账单信息 那分页也应该是调账单信息接口
        this._getNewBillList()
      } else {
        this.getData()
      }
    },
    //删除
    delRecord(data) {
      this.$modal.confirm({
        title: "删除",
        content: "确定删除该条记录?",
        okText: "确定",
        cancelText: "取消",
        onOk: () => {
          this.$apis.DELETESENDRECEIPT({
              ciReceiptSendVos: [
                {receiptNo: data.receiptNo}
              ],
              sendBatchNo: this.sendBatchNo,
            })
            .then((res) => {
              if (res.returnCode == "0000") {
                this.$message.success("删除成功");
                this.getData()
                // this.dataList.splice(index, 1);
              } else {
                this.$message.error(res.returnMsg);
              }
            });
        },
      });
    },
    //导出
    exportEvt(){
      this.$apis.SENDRECEIPTLISTEXPORT({
        sendBatchNo: this.sendBatchNo || undefined
      })
      .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","寄送账单.xls");
        document.body.appendChild(aLink);
        aLink.click();
        document.body.removeChild(aLink);
        window.URL.revokeObjectURL(url);
      }) 
    },
    //添加账单
    addNewBill(){
    //   this.isEditNewBill = !this.isEditNewBill;
      if(this.isEditNewBill){ //保存
        this.addNewCharge()
        .then(()=>{
          this.isEditNewBill = false;
        })
      }else{ //查询所有未加入的账单
        this.pagination.pageNum = 1;
        this.isEditNewBill = true;
        this.cacheDataList = {}
        this._getNewBillList()
      }
    },
    _getNewBillList() {
        this.$apis.QUERYNOSENDRECEIPLIST({
          pageNum: this.pagination.pageNum,
          pageSize: this.pagination.pageSize,
          payorCode: this.form.payorCode,
          ...this.searchData
        })
        .then((res) => {
          if (res.returnCode == "0000") {
            this.selectedRowKeys = [];
            let content = res.content || {};
            this.pagination.total = content.total || 0;
            this.dataList = content.list || [];
            this.cacheDataList[this.pagination.pageNum] = this.dataList
          } else {
            this.$message.error(res.returnMsg);
          }
        });
    },
    checkBeforeSave() {
        if(!this.form.trackingNo){
            this.$message.warning("请输入快递单号");
            return false;
        }
        if(!this.form.sendDate){
            this.$message.warning("请选择寄送日期");
            return false;
        }
        let allData = []
        for(let i in this.cacheDataList){
            allData = allData.concat(this.cacheDataList[i])
        }
        let ciReceiptSendVos = [];
        if(this.isEditNewBill){
            ciReceiptSendVos = [];
            allData.forEach((item,index)=>{
                if(this.selectedRowKeys.indexOf(index)!=-1){
                    ciReceiptSendVos.push({
                        id: item.id,
                        receiptNo: item.receiptNo,
                        selfpaidAmount: item.selfpaidAmount
                    })
                }
            })
        } else {
            ciReceiptSendVos = allData.map(item => {
                return {
                    id: item.id,
                    receiptNo: item.receiptNo,
                    selfpaidAmount: item.selfpaidAmount
                }
            })
        }
        for(let i = 0; i < ciReceiptSendVos.length; i ++) {
            const selfpaidAmount = ciReceiptSendVos[i].selfpaidAmount
            if(selfpaidAmount && !numValid.test(selfpaidAmount)){
                this.$message.warning("请输入正确的客户自付金额");
                return false;
            }
        }
        return {
            ...this.form,
            ciReceiptSendVos: ciReceiptSendVos,
            sendDate: moment(this.form.sendDate).format('YYYY-MM-DD 00:00:00'),
            sendBatchNo: this.sendBatchNo || undefined
        }
    },
    //新建/保存寄送
    addNewCharge(){
      return new Promise((resolve,reject)=>{
        let formData = this.checkBeforeSave()
        if(!formData){
            reject()
            return false;
        }
        this.$apis.SAVERECEIPSENDINFO(formData)
        .then((res) => {
          if (res.returnCode == "0000") {
            this.sendBatchNo = res.content;
            this.$message.success("成功");
            this.selectedRowKeys = [];
            this.cacheDataList = {}
            this.getData();
            resolve();
          } else {
            this.$message.error(res.returnMsg);
            reject();
          }
        });
      })
    }
  },
};
</script>
<style lang="less" scoped>
.none-label {
  text-align: right;
  .ant-form-item-label {
    opacity: 0;
  }
}
.ant-btn .icon-class {
  .mg-r(10);
}
.btn-div{
  justify-content: space-between;
}
</style>