<template>
  <div class="main-contain outpatientChargesManagement">
    <div class="position">
      <bread-crumb :crumbs="crumbs"></bread-crumb>
    </div>
    <div class="app-container">
      <div
        style="
          display: flex;
          justify-content: space-between;
          margin-bottom: 10px;
        ">

      </div>
      <div style="margin-bottom: 10px;">
        <el-date-picker
          size="small"
          v-model="start_time"
          prefix-icon="el-icon-date"
          @change="handleStartTimeChange"
          :editable="false"
          :clearable="false"
          style="width: 196px; "
          type="date"
          placeholder="选择开始日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          align="right"
        ></el-date-picker>
        <span style="text-align: center;">-</span>
        <el-date-picker
          size="small"
          v-model="end_time"
          prefix-icon="el-icon-date"
          @change="handleEndTimeChange"
          :editable="false"
          :clearable="false"
          style="width: 196px; "
          type="date"
          placeholder="选择结束日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          align="right"
        ></el-date-picker>
        <el-button size="small" type="primary"
                   @click="query">查询
        </el-button>
        <el-button size="small" type="primary"
                   @click="login">短信登录税局
        </el-button>
        <el-button size="small" type="primary"
                   @click="auth">认证
        </el-button>
      </div>

      <el-table
        :data="tableData"
        border
        style="width: 100%"
        :row-style="{ color: '#303133' }"
        :header-cell-style="{
          backgroundColor: 'rgb(245, 247, 250)',
          color: '#606266',
        }"
        highlight-current-row
      >
        <el-table-column
          prop="date"
          label="序号"
          width="60"
          align="center"
          type="index"
        >
        </el-table-column>

        <el-table-column align="center" width="90" prop="name" label="患者名字">
          <template slot-scope="scope">{{ scope.row.patient.name }}</template>
        </el-table-column>

        <el-table-column align="center" width="90" prop="name" label="患者性别">
          <template slot-scope="scope">{{ scope.row.patient.gender == 1 ? '男':'女' }}</template>
        </el-table-column>


        <el-table-column align="center" width="90" prop="name" label="处方类型">
          <template slot-scope="scope">
            <div>{{ getMedType(scope.row.med_type) }}</div>
          </template>
        </el-table-column>

        <el-table-column align="center" width="90" prop="name" label="结算类型">
          <template slot-scope="scope">
            <div v-if="scope.row.his_patient.balance_accounts_type != 2">
              医保
            </div>
            <div v-if="scope.row.his_patient.balance_accounts_type == 2">
              自费
            </div>
          </template>
        </el-table-column>

        <el-table-column align="center" width="90" prop="name" label="就诊凭证类型">
          <template slot-scope="scope">
            <div v-if="scope.row.his_patient.id_card_type == 1">
              社会保障卡
            </div>
            <div v-if="scope.row.his_patient.id_card_type == 2">
              居民身份证
            </div>
            <div v-if="scope.row.his_patient.id_card_type == 4">
              医保电子凭证
            </div>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          width="100"
          prop="name"
          label="处方日期"
        >
          <template slot-scope="scope">
            {{getTimes(scope.row.settle_accounts_date) }}
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          width="100"
          prop="name"
          label="收费时间"
        >
          <template slot-scope="scope">
            {{
              scope.row.setl_time
                ? scope.row.setl_time
                : getTimes(scope.row.settle_accounts_date)
            }}
          </template>
        </el-table-column>

        <el-table-column align="center" width="90" prop="name" label="收费员">
          <template slot-scope="scope">
            {{getName(scope.row.creator)}}
          </template>
        </el-table-column>

        <el-table-column align="center" prop="name" label="操作">
          <template slot-scope="scope">
            <el-button v-if="scope.row.result.id == 0" size="mini" type="primary"
                        @click="blue(scope.row)">
              开票
            </el-button>
            <el-button v-if="scope.row.result.id > 0 && scope.row.result.is_red_washed == 0" size="mini" type="primary"
                        @click="hongchong(scope.row)">
              红冲
            </el-button>
            <el-button size="mini" type="primary" v-if="scope.row.result.id > 0 && scope.row.result.is_red_washed == 0"
                       @click="yulan(scope.row)">
              预览
            </el-button>
            <el-button size="mini" type="primary" @click="download(scope.row)"  v-if="scope.row.result.id > 0 && scope.row.result.is_red_washed == 0">
              下载
            </el-button>


          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[10, 50, 100]"
        :page-size="10"
        :current-page.sync="page"
        background
        style="margin-top: 20px; float: right"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <el-dialog
      title="登录"
      :visible.sync="login_dialogVisible"
      width="40%"
    >
      <div>
        <el-form :rules="rules" :label-position="labelPosition" label-width="100px" :model="formLabelAlign">
<!--          <el-form-item label="税局账号">-->
<!--            <el-input v-model="formLabelAlign.name"></el-input>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="税局密码">-->
<!--            <el-input v-model="formLabelAlign.region"></el-input>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="手机号码">-->
<!--            <el-input v-model="formLabelAlign.type"></el-input>-->
<!--          </el-form-item>-->
          <el-form-item label="短信验证码" prop="verify">
            <div style="display: inline-block;width: 50%;">
              <el-input v-model="formLabelAlign.verify"></el-input>
            </div>
            <div style="display: inline-block;">
              <el-button :disabled="countdown > 0" @click="verify_click">{{countdown > 0?countdown:'获取短信验证码'}}</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="login_dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="loginSJ()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 二维码 -->
    <el-dialog
      title="提示"
      :visible.sync="qr_dialogVisible"
      width="30%"
      center
    >
      <div style="margin: auto;width: 120px;">
        <div class="qrcode" ref="qrCodeUrl"></div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="qr_dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="qr_dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>


<script>
import BreadCrumb from '@/xt_pages/components/bread-crumb'
import { getDoctorList, getExportConsumeDetailList, getHisOrderList, Refund } from '@/api/his/his'
import { ModifyFapiaoCode } from '@/api/his/his_tools'


// import NewStatementPrint from './newStatementPrint'
import { adminMainView} from "@/api/role/admin";
import { fetchAllAdminUsers } from '@/api/doctor'
import axios from 'axios'
import { jsGetAge, uParseTime } from '@/utils/tools'
import {
  getOrderFapiaoList,
  OpenBlueFapiao,
  OpenRedFapiao,
  GetSMSCode,
  SMSLogin, GetQRCode
} from '../../api/fapiao'

import { getDialysisRecordInitData } from '@/api/dialysis_record'
import QRCode from 'qrcodejs2'
const moment = require('moment')
export default {
  name: 'OutpatientChargesSummary',
  components: {
    BreadCrumb,
  },
  data() {
    return {
      staff:"",
      admins:[],
      orderObj: {},
      batchOrderObj: {},
      fapiao_number:"",
      med_options: [
        { id: 0, text: '全部' },
        { id: 11, text: '普通门诊' },
        { id: 14, text: '门诊特殊病' }
      ],
      zone_options: [
        { id: 0, text: '全部分区' }
      ],
      statementListVisible: false,
      statementVisible: false,
      batchStatementVisible: false,
      statementVisible9504: false,
      orderObj9504: {},
      crumbs: [
        { path: false, name: '门诊收费' },
        { path: false, name: '项目消费明细汇总' }
      ],
      tableData: [],
      tableData2:[],
      selecting_schs: [],
      dialogfapiaoVisible:false,
      targeOrderId:0,
      targeObj:{},
      limit: 10,
      page: 1,
      keywords: '',
      sch_type: '0',//班次
      zoneVal: 0,//分区
      medTypeVal: 0,
      start_time: moment(new Date()).add('year', 0).format('YYYY-MM-DD'),
      end_time: moment(new Date()).add('year', 0).format('YYYY-MM-DD'),
      pay_time:"",
      total: '',
      doctors: [],
      sort_type: 1,
      sort_types: [
        { value: 1, label: '处方时间' },
        { value: 2, label: '结算时间' }
      ],
      admin_user_id: '',
      listVisible: false,
      allListVisible: false,
      adminUserOptions: [],
      invoiceVisible: false,
      paramsObj: {},
      invoiceParams: {},
      settlementVisible: false,
      settlementObj: {},
      accounts_click_vi:false,

      login_dialogVisible:false,
      qr_dialogVisible:false,
      formLabelAlign: {
        name: '',
        region: '',
        type: '',
        verify:'',
      },
      rules:{
        verify:[{ required: true, message: '请输入活动名称', trigger: 'blur' },]
      },
      time:null,
      countdown: 0,

    }
  },

  created() {
    this.getInitData()
    this.fetchAllAdminUsers()
    // this.getDoctorList()
    this.getHisOrderList()
    // this.getAllstaff()
  },

  methods: {
    loginSJ(){
      // let params = {
      //   "code":this.formLabelAlign.verify,
      // }
      // SMSLogin(params).then((response) => {
      //   if (response.data.state == 0) {
      //     this.login_dialogVisible = false
      //     this.$message.error(response.data.msg)
      //     return false
      //   } else {
      //     this.login_dialogVisible = false
      //     // this.$message.success(response.data.msg)
      //     // this.$message.success(response.data.data.msg)
      //     this
      //       .$confirm(response.data.data.msg, '信息', {
      //         confirmButtonText: '确 定',
      //         type: 'warning'
      //       })
      //       .then(() => {
      //       })
      //       .catch(() => {
      //       })
      //
      //   }
      // })

      var that = this;
      let params = {
        "code":this.formLabelAlign.verify,
      }
      axios.get('http://127.0.0.1:9532/api/fapiao/sms/login',{params:params}).then(function(response) {
        if (response.data.state == 0) {
          that.$message.error(response.data.data.msg);
          return false
        } else {
          if(response.data.data.failed_code == -10){
            that.$confirm(response.data.data.msg, '错误信息', {
              confirmButtonText: '确 定',
              type: 'warning'
            }).then(() => {

            }).catch(() => {
            })
          }else{
            that.login_dialogVisible = false
            // this.$message.success(response.data.msg)
            // this.$message.success(response.data.data.msg)
            that
              .$confirm(response.data.data.msg, '信息', {
                confirmButtonText: '确 定',
                type: 'warning'
              })
              .then(() => {
              })
              .catch(() => {
              })
          }

        }
      }).catch(function(error) {
      })

    },
    login(){
      this.login_dialogVisible = true
    },
    verify_click(){
      var that = this;
      let params = {
        "admin_user_id":this.$store.getters.xt_user.user.id,
      }
      axios.get('http://127.0.0.1:9532/api/fapiao/sms/code',{params:params}).then(function(response) {
        if (response.data.state == 0) {
          that.$message.error(response.data.data.msg);
          return false
        } else {
          if(response.data.data.failed_code == -10){
            that.$confirm(response.data.data.msg, '错误信息', {
              confirmButtonText: '确 定',
              type: 'warning'
            }).then(() => {

            }).catch(() => {
            })
          }else{
            that.$message.success(response.data.data.msg)
          }

        }
      }).catch(function(error) {
      })
      this.countdown = 60
      this.time = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--
        } else {
          clearInterval(this.time)
        }
      }, 1000)
    },
    auth(){

      // let params = {
      // }
      // GetQRCode(params).then((response) => {
      //   if (response.data.state == 0) {
      //     this.$message.error(response.data.msg)
      //     return false
      //   } else {
      //     if(response.data.data.cus_status == 1){
      //       this.$nextTick(() =>{
      //         var qrcode = new QRCode(this.$refs.qrCodeUrl, {
      //           text: response.data.data.qr_code, // 需要转换为二维码的内容
      //           width: 120,
      //           height: 120,
      //           colorDark: '#000000',
      //           colorLight: '#ffffff',
      //           correctLevel: QRCode.CorrectLevel.H
      //         })
      //       })
      //       this.qr_dialogVisible =true
      //     }else if(response.data.data.cus_status == -1){
      //       // this.$message.error(response.data.msg)/*  */
      //       this
      //         .$confirm(response.data.data.msg, '信息', {
      //           confirmButtonText: '确 定',
      //           type: 'warning'
      //         })
      //         .then(() => {
      //         })
      //         .catch(() => {
      //         })
      //     }else if(response.data.data.cus_status == 2){
      //       // this.$message.error(response.data.data.msg)
      //       this
      //         .$confirm(response.data.data.msg, '信息', {
      //           confirmButtonText: '确 定',
      //           type: 'warning'
      //         })
      //         .then(() => {
      //         })
      //         .catch(() => {
      //         })
      //
      //     }else if(response.data.data.cus_status == -3){
      //       // this.$message.error(response.data.data.msg)
      //       this
      //         .$confirm(response.data.data.msg, '信息', {
      //           confirmButtonText: '确 定',
      //           type: 'warning'
      //         })
      //         .then(() => {
      //         })
      //         .catch(() => {
      //         })
      //
      //     }else if(response.data.data.cus_status == -4){
      //       // this.$message.error(response.data.data.msg)
      //       this
      //         .$confirm(response.data.data.msg, '信息', {
      //           confirmButtonText: '确 定',
      //           type: 'warning'
      //         })
      //         .then(() => {
      //         })
      //         .catch(() => {
      //         })
      //
      //     }
      //     // this.$message.success(response.data.msg)
      //   }
      // })


      var that = this;
      let params = {
        "admin_user_id":this.$store.getters.xt_user.user.id,
      }
      axios.get('http://127.0.0.1:9532/api/fapiao/qrcode/get',{params:params}).then(function(response) {
        if (response.data.state == 0) {
          that.$message.error(response.data.data.msg);
          return false
        } else {
          if(response.data.data.failed_code == -10){
            that.$confirm(response.data.data.msg, '错误信息', {
              confirmButtonText: '确 定',
              type: 'warning'
            }).then(() => {

            }).catch(() => {
            })
          }else{
            if(response.data.data.cus_status == 1){
              this.$nextTick(() =>{
                var qrcode = new QRCode(that.$refs.qrCodeUrl, {
                  text: response.data.data.qr_code, // 需要转换为二维码的内容
                  width: 120,
                  height: 120,
                  colorDark: '#000000',
                  colorLight: '#ffffff',
                  correctLevel: QRCode.CorrectLevel.H
                })
              })
              this.qr_dialogVisible =true
            }else if(response.data.data.cus_status == -1){
              // this.$message.error(response.data.msg)/*  */
              that
                .$confirm(response.data.data.msg, '信息', {
                  confirmButtonText: '确 定',
                  type: 'warning'
                })
                .then(() => {
                })
                .catch(() => {
                })
            }else if(response.data.data.cus_status == 2){
              // this.$message.error(response.data.data.msg)
              that
                .$confirm(response.data.data.msg, '信息', {
                  confirmButtonText: '确 定',
                  type: 'warning'
                })
                .then(() => {
                })
                .catch(() => {
                })

            }else if(response.data.data.cus_status == -3){
              // this.$message.error(response.data.data.msg)
              that
                .$confirm(response.data.data.msg, '信息', {
                  confirmButtonText: '确 定',
                  type: 'warning'
                })
                .then(() => {
                })
                .catch(() => {
                })

            }else if(response.data.data.cus_status == -4){
              // this.$message.error(response.data.data.msg)
              that
                .$confirm(response.data.data.msg, '信息', {
                  confirmButtonText: '确 定',
                  type: 'warning'
                })
                .then(() => {
                })
                .catch(() => {
                })
            }

          }

        }
      }).catch(function(error) {
      })

    },
    query(){
      this.getHisOrderList()
    },download(){


    },
    blue(row){
     var  ids = row.id
      let params = {
        "order_ids":ids,
        "admin_user_id":this.$store.getters.xt_user.user.id,
      }

      var that = this;
      axios.get('http://127.0.0.1:9532/api/fapiao/blue',{params:params}).then(function(response) {
        if (response.data.state == 0) {
          that.$message.error(response.data.data.msg);
          return false
        } else {
          if(response.data.data.failed_code == -10){
            that.$confirm(response.data.data.msg, '错误信息', {
              confirmButtonText: '确 定',
              type: 'warning'
            }).then(() => {

            }).catch(() => {
            })
          }else{
            that.$message.success(response.data.data.msg)
            that.getHisOrderList()
          }

        }
      }).catch(function(error) {
      })
      // OpenBlueFapiao(params).then((response) => {
      //   if (response.data.state == 0) {
      //     this.$message.error(response.data.msg)
      //     return false
      //   } else {
      //     this.$message.success(response.data.msg)
      //     this.getHisOrderList()
      //   }
      // })


    }, yulan(row){



    },hongchong(row){
      var  id = row.result.id

      let params = {
        "id":id,
        "admin_user_id":this.$store.getters.xt_user.user.id,
      }

      var that = this;
      axios.get('http://127.0.0.1:9532/api/fapiao/red',{params:params}).then(function(response) {
        if (response.data.state == 0) {
          that.$message.error(response.data.data.msg);
          return false
        } else {
          if(response.data.data.failed_code == -10){
            that.$confirm(response.data.data.msg, '错误信息', {
              confirmButtonText: '确 定',
              type: 'warning'
            }).then(() => {

            }).catch(() => {
            })
          }else{
            that.$message.success(response.data.msg)
            that.getHisOrderList()
          }

        }
      }).catch(function(error) {
      })

    },
    getAllstaff(){
      adminMainView()
        .then(rs => {

          var resp = rs.data;
          if (resp.state === 1) {
            var adminData = resp.data.admins
            this.admins.push(...adminData);
          } else {
            this.$message.error(resp.msg);
          }
        })
        .catch(err => {
          this.$message.error(err);
        });


    },

    handleSelectionChange(val) {
      this.selecting_schs = val
    },
    handleSchType(val) {
      this.sch_type = val
      this.getHisOrderList()
    }, handleMedChange() {
      this.getHisOrderList()
    },
    handleZoneChange(val) {
      this.zoneVal = val
      this.getHisOrderList()

    },
    getInitData: function() {
      getDialysisRecordInitData().then((rs) => {
        var resp = rs.data
        if (resp.state == 1) {
          var zones = resp.data.zones
          var zone_options = [{ id: 0, text: '全部' }]
          for (let z_i = 0; z_i < zones.length; z_i++) {
            const zone = zones[z_i]
            zone_options.push({ id: zone.id, text: zone.name })
          }
          this.zone_options = zone_options

        } else {
          this.$message.error(resp.msg)
        }
      })
    },



    getMedType(med_type) {
      var med_type = parseInt(med_type)
      switch (med_type) {
        case 11:
          return '普通门诊'
          break
        case 12:
          return '门诊挂号'
          break
        case 13:
          return '急诊'
          break
        case 14:
          return '门诊特殊病'
          break
        case 15:
          return '门诊统筹'
          break
        case 16:
          return '门诊慢性病'
          break
        case 21:
          return '普通住院'
          break
        case 140104:
          return '城乡门诊特殊病(140104)'
          break
        case 992102:
          return '单病种(992102)'
          break
      }
    },


    fetchAllAdminUsers() {
      fetchAllAdminUsers().then((response) => {
        if (response.data.state == 1) {
          this.adminUserOptions = response.data.data.users
        }
      })
    },
    getName(admin_user_id) {
      for (let i = 0; i < this.adminUserOptions.length; i++) {
        if (this.adminUserOptions[i].id == admin_user_id) {
          return this.adminUserOptions[i].name
        }
      }
    },



    handleSizeChange(limit) {
      this.limit = limit
      this.getHisOrderList()
    },
    handleCurrentChange(page) {
      this.page = page
      this.getHisOrderList()
    },
    handleStartTimeChange() {
      this.page = 1
      this.keywords = ''
      this.getHisOrderList()
    },
    handleEndTimeChange() {
      this.page = 1
      this.keywords = ''
      this.getHisOrderList()
    },

    getTimes(time) {
      return uParseTime(time, '{y}-{m}-{d}')
    },

    getTime(value, temp) {
      if (value != undefined) {
        return uParseTime(value, temp)
      }
      return ''
    },
    getHisOrderList() {
      let params = {
        page: this.page,
        limit: this.limit,
        keywords: this.keywords,
        start_time: this.start_time,
        end_time: this.end_time,
        sort_type: this.sort_type,
      }
      getOrderFapiaoList(params).then((response) => {
        if (response.data.state == 0) {
          this.$message.error(response.data.msg)
          return false
        } else {
          this.tableData = response.data.data.order
          this.total = response.data.data.total
        }
      })
    },
    getDoctorList() {
      getDoctorList().then((response) => {
        if (response.data.state == 0) {
          this.$message.error(response.data.msg)
          return false
        } else {
          this.doctors = response.data.data.doctors
        }
      })
    },
    open(index) {
      if (index == 1) {
        this.listVisible = true
      } else if (index == 2) {
        this.allListVisible = true
      }
    }, unique(array) {
      // res用来存储结果
      var res = []
      for (var i = 0, arrayLen = array.length; i < arrayLen; i++) {
        for (var j = 0, resLen = res.length; j < resLen; j++) {
          if (array[i].id === res[j].id && array[i].price === res[j].price) {
            break
          }
        }
        // 如果array[i]是唯一的，那么执行完循环，j等于resLen
        if (j === resLen) {
          res.push(array[i])
        }
      }
      return res
    },camcleModifyFaPiaoCode(){
      this.dialogfapiaoVisible = false
      this.invoiceVisible = true
      var obj = this.targeObj
      let paramsObj = {
        order_id: obj.id,
        patient_id: obj.patient_id,
        number: obj.mdtrt_id,
        name: obj.patient.name,
        age: obj.age,
        gend: obj.patient.gender,
        setl_time: obj.setl_time,
        chargeName: this.getName(obj.creator)
      }
      this.dialogfapiaoVisible = false
      this.invoiceParams = paramsObj
      this.invoiceVisible = true
    },modifyFaPiaoCode(){
      let params = {
        id:this.targeOrderId,
        fapiao_number: this.fapiao_number
      }
      modifyFapiaoCodetwo(params).then((response) => {
        if (response.data.state == 0) {
          this.$message.error(response.data.msg)
          return false
        } else {
          var obj = this.targeObj
          let paramsObj = {
            order_id: obj.id,
            patient_id: obj.patient_id,
            number: obj.mdtrt_id,
            name: obj.patient.name,
            age: obj.age,
            gend: obj.patient.gender,
            setl_time: obj.setl_time,
            chargeName: this.getName(obj.creator)
          }
          this.dialogfapiaoVisible = false
          this.invoiceParams = paramsObj
          this.invoiceVisible = true
          this.getHisOrderList()
        }
      })

    },

    invoicePrint(obj) {
      if(this.$store.getters.xt_user.org_id == 10480 || this.$store.getters.xt_user.org_id == 0){
        this.fapiao_number  = obj.fa_piao_number
        this.dialogfapiaoVisible = true
        this.targeOrderId = obj.id
        this.targeObj = obj
      }else{
        let paramsObj = {
          order_id: obj.id,
          patient_id: obj.patient_id,
          number: obj.mdtrt_id,
          name: obj.patient.name,
          age: obj.age,
          gend: obj.patient.gender,
          setl_time: obj.setl_time,
          chargeName: this.getName(obj.creator)
        }
        this.dialogfapiaoVisible = false
        this.invoiceParams = paramsObj
        this.invoiceVisible = true


      }


    }
  },
  watch:{
    countdown(news,old){
      if(this.countdown ==0){
        clearInterval(this.time)
      }

    }

  }
}
</script>
<style lang="scss">
.table{
tr td{
  padding:5px 0;
}
}
</style>
