<template>
  <div>
    <el-dialog title="透析下机" class="newDialog" :visible.sync="visible" width="854px" :modal-append-to-body="false">
      <!-- <div class="txsj">
      </div> -->
      <div class="warnTxt" v-if="showTxt != ''">{{ showTxt }}</div>
      <el-form :model="form" label-width="100px">
        <el-form-item label="下机护士">
          <el-select v-model="form.nurse_id" :disabled="!(dialysis_order.id != 0)">
            <el-option v-for="(admin, index) in admins" :key="index" :value="admin.id" :label="admin.name"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="下机时间 :" style="width:275px">
          <el-date-picker
            type="datetime"
            format="yyyy-MM-dd HH:mm"
            value-format="yyyy-MM-dd HH:mm"
            placeholder="选择时间"
            v-model="end_time"
            style="width:100%;"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="穿刺处血肿:" v-if="isShowFiled('穿刺处血肿')" :label-width="150">
           <el-radio-group v-model="form.puncture_point_haematoma">
              <el-radio :label="1">有</el-radio>
              <el-radio :label="2">无</el-radio>
           </el-radio-group>
        </el-form-item>

        <el-form-item label="内瘘: " v-if="isShowFiled('内瘘')">
            <el-input v-model="form.internal_fistula" readonly  @focus="showInnerDialog('7')" style="width:200px"></el-input>
        </el-form-item>


        <el-form-item label="导管: " v-if="isShowFiled('导管')">
          <el-input v-model="form.catheter" @focus="showInnerDialog('4')" style="width:200px"></el-input>
        </el-form-item>

        <el-form-item label="透析器凝血: " v-if="isShowFiled('透析器凝血')">
          <el-input
            style="width:200px"
            v-model="form.cruor"
            readonly
            @focus="showInnerDialog('1')"
          ></el-input>
       </el-form-item>

        <el-form-item>
          <el-button v-if="(dialysis_order.id != 0 && dialysis_order.stage == 1)" @click="submit" :loading="loading"
                     type="primary">执行下机
          </el-button>
          <el-button
            v-if="dialysis_order.stage == 2 "
            type="primary" @click="modifyFinish">修改下机
          </el-button>
        </el-form-item>



      </el-form>
    </el-dialog>

    <multi-select-box
      :propsForm="InnerDialogProps"
      v-on:dialog-comfirm="innerDialogComfirm"
      v-on:dialog-cancle="innerDialogCancle"
    ></multi-select-box>

  </div>
</template>

<script>
  import axios from 'axios'
  import { finishDialysis,PostModifyFinishDialysis } from '@/api/dialysis_record'
  import { parseTime } from '@/utils'
  import multiSelectBox from './MultiSelectBox'
  import request from '@/utils/request'
  import store from "@/store";
  import { getDataConfig } from '@/utils/data'
  export default {
    components: {
      multiSelectBox
    },
    name: 'FinishDialog',
    data() {
      return {
        showTxt:'',
        hasPermission:true,
        visible: false,
        loading: false,
        creator: 0,
        patient_id: 0,
        schedule_date: 0,
        isPremission:false,
        end_time: '',
        isVisibility: false,
        form: {
          nurse_id: 0,
          puncture_point_haematoma:2,
          internal_fistula:"",
          catheter:"",
          cruor:"",
        },
        internal_fistula: [],
        InnerDialogProps: {
          values: [],
          visibility: false,
          isShowTextArea: true,
          customContent: '',
          titles: '',
          type: '' // 不同弹框类型，用来匹配数据
        },
        catheter: [],
        cruorOptions: [],
      }
    },
    props: {
      prescription: { // 透析处方
        type: Object,
      },
      dialysis_order: {
        type: Object
      },
      schedule: {
        type: Object
      },
      admins: {
        type: Array
      }, special_premission: {
        type: Array,
      },
      patient:{
        type: Object
      }
    },
    created() {
      this.internal_fistula = getDataConfig('hemodialysis', 'internal_fistula')
      this.catheter = getDataConfig('hemodialysis', 'catheter')
      this.cruorOptions = getDataConfig('hemodialysis', 'cruor')
    },
    watch: {
      'dialysis_order.id': function() {
        if (this.dialysis_order.id == 0) {
          this.form.nurse_id = 0
        } else if (this.dialysis_order.stage == 1) {
          this.form.nurse_id = this.$store.getters.xt_user.user.id
        } else {
          console.log("orde32332323232332",this.dialysis_order)
          this.form.nurse_id = this.dialysis_order.finish_nurse
          this.form.catheter = this.dialysis_order.catheter
          this.form.cruor = this.dialysis_order.cruor
          this.form.internal_fistula = this.dialysis_order.blood_access_internal_fistula
          this.form.puncture_point_haematoma = this.dialysis_order.puncture_point_haematoma
        }
      },
      patient:{
        handler(newVal){
          this.patient_id = newVal.id
        },
        deep:true
      }
    },
    methods: {
       isShowFiled(name) {
        var filedList = store.getters.xt_user.fileds

        for (let i = 0; i < filedList.length; i++) {
          if (filedList[i].module == 9 && filedList[i].filed_name_cn == name && filedList[i].is_show == 1) {
            return true
          }
        }
        return false
      },
      show: function(record) {
        this.record = record
        console.log("下机",record)
        this.getPermission()
        this.visible = true
        var nowDate = new Date()
        var nowYear = nowDate.getFullYear()
        var nowMonth = nowDate.getMonth() + 1
        var nowDay = nowDate.getDate()
        var nowHours = nowDate.getHours()
        var nowMinutes = nowDate.getMinutes()
        var time =
          nowYear +
          '-' +
          (nowMonth < 10 ? '0' + nowMonth : nowMonth) +
          '-' +
          (nowDay < 10 ? '0' + nowDay : nowDay) + ' ' + (nowHours < 10 ? '0' + nowHours : nowHours) + ':' + (nowMinutes < 10 ? '0' + nowMinutes : nowMinutes)
        if(this.$route.query.patient_id){
          this.patient_id = this.$route.query.patient_id
        }

        this.schedule_date = this.$route.query.date

        if (this.dialysis_order.id == 0) {
          this.form.nurse_id = 0
        } else if (this.dialysis_order.stage == 1) {
          this.form.nurse_id = this.$store.getters.xt_user.user.id
        } else {
          this.form.nurse_id = this.dialysis_order.finish_nurse
        }


        if (this.dialysis_order.finish_creator > 0) {
          for (let i = 0; i < this.special_premission.length; i++) {
            if (this.$store.getters.xt_user.user.id == this.special_premission[i].admin_user_id) {
              this.isPremission = true
            }
          }
        }

        if (this.dialysis_order.finish_creator > 0) {
            this.creator = this.dialysis_order.finish_creator
        }


        if (this.dialysis_order.id == "") {
          //没有上下机记录
          this.end_time = this.dialysis_order.finish_creator == 0 ? time : this.getTime(this.dialysis_order.end_time, '{y}-{m}-{d} {h}:{i}')

        } else {
          if (this.dialysis_order.start_time > 0) {
            if (this.prescription.id != "") {
              let endTime = 0;
              endTime =
                this.dialysis_order.start_time +
                this.prescription.dialysis_duration_hour * 3600 +
                this.prescription.dialysis_duration_minute * 60;
              this.end_time = parseTime(endTime, "{y}-{m}-{d} {h}:{i}");
            } else {
              this.end_time =
                parseTime(Date.parse(new Date()) / 1000, "{y}-{m}-{d} {h}:{i}")
            }
            if (this.dialysis_order.end_time > 0) {
              this.end_time =
                parseTime(this.dialysis_order.end_time, "{y}-{m}-{d} {h}:{i}");
            }
          } else {
            this.end_time = this.dialysis_order.finish_creator == 0 ? time : this.getTime(this.dialysis_order.end_time, '{y}-{m}-{d} {h}:{i}')

          }
        }


      },
      hide: function() {
        this.visible = false
      },
      modifyFinish:function(){
        let ParamsQuery = {};
        ParamsQuery["id"] = this.dialysis_order.id;
        ParamsQuery["nurse"] = this.form.nurse_id;
        ParamsQuery["end_time"] = this.end_time;
        ParamsQuery["mode"] = "2"
        ParamsQuery["puncture_point_haematoma"] = parseInt(this.form.puncture_point_haematoma)
        ParamsQuery["internal_fistula"] = this.form.internal_fistula
        ParamsQuery["catheter"] = this.form.catheter
        ParamsQuery["cruor"] = this.form.cruor
        if(this.dialysis_order.finish_creator  != this.$store.getters.xt_user.user.id){
          ParamsQuery["mode"] = "3"
        }
        PostModifyFinishDialysis(ParamsQuery).then(response => {
          if (response.data.state == 0) {
            this.$message.error(response.data.msg)

            return false;
          } else {
            this.$message.success("修改成功")
            var record = this.dialysis_order;
            for (const key in response.data.data.dialysis_order) {
              this.$set(record, key, response.data.data.dialysis_order[key]);
            }
            console.log(response.data.data.after)
            this.$emit('assessmentAfterDislysis', response.data.data.after)
          }
        });


      },
      submit: function() {
        this.loading = true
        let mode = "1"
        finishDialysis(this.patient_id,this.schedule_date ? parseTime(this.schedule_date, '{y}-{m}-{d}') : parseTime(new Date(), '{y}-{m}-{d}'), this.end_time, this.form.nurse_id,mode,parseInt(this.form.puncture_point_haematoma),this.form.internal_fistula,this.form.catheter,this.form.cruor).then(rs => {
          this.loading = false
          var resp = rs.data
          if (resp.state == 1) {
            var dialysis_order = resp.data.dialysis_order
            var this_order = this.dialysis_order
            for (const key in dialysis_order) {
              this.$set(this_order, key, dialysis_order[key])
            }
            let orgId = parseInt(sessionStorage.getItem("org_id"));
            this.hide()
            this.$emit('assessmentAfterDislysis', resp.data.assessmentAfterDislysis)

          } else {
            this.$message.error(resp.msg)
          }
        })
      }, getTime(value, temp) {
        if (value != undefined) {
          return parseTime(value, temp)
        }
        return ''
      },
      getPermission(){
      request.get("/api/func_per/get",{
        params:{
          create_url:"/api/dialysis/finish?mode=1",
          modify_url:"/api/finish_dialysis/modify?mode=2",
          modify_other_url:"/api/finish_dialysis/modify?mode=3",
          module:6
        }
      }).then(res => {
        if(res.data.state == 0){
          this.hasPermission = false
        }else if(res.data.state == 1){
          if(this.record.id != "" && this.record.creater != 0){//有数据
            if(this.record.creater == this.$store.getters.xt_user.user.id){//创建人是自己
              if(res.data.data.is_has_modify == false){
                this.hasPermission = false
                this.showTxt = "你没有修改执行下机权限"
              }
            }else{//创建人不是自己
              if(res.data.data.is_has_modify_other == false){
                this.hasPermission = false
                this.showTxt = "你没有修改他人执行下机权限"
              }
            }
          }else if(this.record.id == "" || this.record.creater == 0){
            if(res.data.data.is_has_create  == false){
              this.hasPermission = false
              this.showTxt = "你没有执行下机权限"
            }
          }
        }
      })
    },
    showInnerDialog: function(val) {
        this.InnerDialogProps.visibility = true
        switch (val) {
          case '7': // 内瘘
            this.InnerDialogProps.values = this.internal_fistula
            this.InnerDialogProps.titles = '内瘘'
            this.InnerDialogProps.type = 'internal_fistula'
            this.InnerDialogProps.selected = this.form.internal_fistula
            this.InnerDialogProps.isShowTextArea = false
            break
           case '4': // 导管
            this.InnerDialogProps.values = this.catheter
            this.InnerDialogProps.titles = '导管'
            this.InnerDialogProps.type = 'catheter'
            this.InnerDialogProps.selected = this.form.catheter
            this.InnerDialogProps.isShowTextArea = false
            break
            case '1':
            this.InnerDialogProps.values = this.cruorOptions
            this.InnerDialogProps.titles = '凝血'
            this.InnerDialogProps.type = 'cruor'
            this.InnerDialogProps.selected = this.form.cruor
            this.InnerDialogProps.isShowTextArea = false
            break

        }
      },
      innerDialogComfirm: function(val) {
        this.InnerDialogProps.visibility = false
        switch (val.type) {
          case 'internal_fistula':
            this.form.internal_fistula = val.value.join(',')
            break
          case 'catheter':
            this.form.catheter = val.value.join(',')
            break
          case 'cruor':
          this.form.cruor = val.value.join(',')
          break
        }
      },
      innerDialogCancle: function() {
        this.InnerDialogProps.visibility = false
      },
    }
  }
</script>


<style scoped>
  .txsj {
    text-align: center;
    margin-bottom: 20px;
  }
.warnTxt{
  text-align: center;
  margin: 0 auto;
  background: #faa331;
  max-width: 240px;
  padding: 10px 20px;
  border-radius: 4px;
  margin-bottom: 10px;
  color:#fff;
}
</style>
<style lang="scss">
.newDialog{
  .el-dialog__body{
    padding: 10px 20px 30px;
  }
}
</style>
