<template>
  <service-view v-ref:serviceview :data="show_data" v-if="showview"></service-view>
</template>
<script>
  import {HttpResetClass} from 'vue-client'
  import Vue from 'vue'
  export default {
    title: '报建功能业务控制层',
    props: ['selectdata'],
    data () {
      return {
        show_data: null, // 给通用页面显示的数据
        showview: false, // 控制通用页面
        recording: 0, // 是否有缴费记录
      }
    },
    ready () {
      this.refurbish()
    },
    methods: {
      // 判断是否有缴费记录
        getCheckPayRecording () {
        let http = new HttpResetClass()
        let data = {
          f_process_id: this.selectdata.f_process_id,
          user: this.$login.f,
          paynum:'',
        }
        let res =  http.load('POST', 'rs/logic/getCheckPay', {data:data}, {
          resolveMsg: null,
          rejectMsg: '缴费记录查询失败！！！'
        })
        // 有缴费记录
        if (res.data> 0) {
          this.recording = 1

        }
      },
     modifData(fields,falg){
      fields.forEach(item => {
      if((item.label=='工程费单价'||item.label=='应交总金额'|| item.label=='未结总金额')&&falg==1){
        this.readwriteLabels(item.label)
      }
        if((item.label=='工程费单价'||item.label=='应交总金额'|| item.label=='未结总金额')&&falg==0){
          this.readonlyLabels(item.label)
        }
    })
  },
      //根据缴费记录判断是否可编辑
      async getCheckPay (fields, defname,type) {
        console.log(fields)
        let http = new HttpResetClass()
        let data = {
          f_process_id: this.selectdata.f_process_id,
          user: this.$login.f,
          paynum:'',
        }
        let res = await http.load('POST', 'rs/logic/getCheckPay', {data:data}, {
          resolveMsg: null,
          rejectMsg: '缴费记录查询失败！！！'
        })
        // 有缴费记录
        if (res.data> 0) {
        if(type=='非民用报建'||type=='设备变更'){
          if(defname=='报装缴费'){
            fields.forEach(item => {
              if(item.label=='收费标准备注'){
                this.showLabels(item.label)
              }
            })
          }
        }
          //使用foreach遍历fields
          if(defname=='报装缴费'){
            fields.forEach(item => {
              if(item.label=='收费标准备注'||item.label=='票据类型'||item.label=='报警器'||item.label=='购货单位识别号'||item.label=='购货单位名称'||item.label=='购货单位开户'||item.label=='购货单位地址电话'||item.label=='购货单位银行账号'){
                this.readonlyLabels(item.label)
              }
            })
          }
        }else{ //无缴费记录
          if(type=='非民用报建'||type=='设备变更'){
            if(defname=='报装缴费'){
              fields.forEach(item => {
                if(item.label=='收费标准备注'){
                 this.showLabels(item.label)
                }
              })
            }
          }
          if(defname=='报装缴费'){
            fields.forEach(item => {
              if(item.label=='收费标准备注'||item.label=='票据类型'||item.label=='报警器'||item.label=='购货单位识别号'||item.label=='购货单位名称'||item.label=='购货单位开户'||item.label=='购货单位地址电话'||item.label=='购货单位银行账号'){
                this.readwriteLabels(item.label)
              }
            })
          }
        }
      },
      async refurbish () {
        // fields 字段填充值
        for (const item of this.selectdata.fields) {
          if (!item.value) {
            item.value = null
          }
          if (!item.value && (item.default || item.default === 0) && item.type !== 'datepicker') {
            if (item.eval) {
              item.value = eval(item.default)
            } else {
              item.value = item.default
            }
          }
          if (this.selectdata[item.field]) {
            // 将json字符串格式化赋值给value
            if (String(this.selectdata[item.field]).startsWith("{")) {
              item.value = JSON.parse(this.selectdata[item.field])
            } else {
              item.value = this.selectdata[item.field]
            }
          }
          if (this.selectdata[item.field] === 0) {
            item.value = 0
          }

          // datepicker
          if (item.type === 'datepicker' && !item.value && item.default) {
            item.value = new Date().Format(`${item.format ? item.format : 'yyyy-MM-dd HH:mm:ss'}`)
          }

          // 如果配置类型为select,优先从参数列表获取options
          if (item.type === 'select' || item.type === 'checkbox') {
            if (item.param) {
              let temp = this.$appdata.getParam(item.label)

              if (temp && temp.length > 0) {
                item.options = temp
              }
              if (item.paramLabel) {
                temp = this.$appdata.getParam(item.paramLabel)
                if (temp && temp.length > 0) {
                  item.options = temp
                }
              }
            }
            if (item.ready) {
              item.options = await this[item.ready]()
            }
          }
          if (item.type === 'checkbox') {
            if (this.selectdata[item.field]) {
              item.value = JSON.parse(this.selectdata[item.field])
            } else {
              item.value = []
            }
          }
        }
        // 控制组件
        if (this.selectdata.components) {
          this.selectdata.components.forEach(item => {
            item.mark = 2
          })
        }
        // 初始化onetomany
        if (this.selectdata.onetomany) {
          for (const item of this.selectdata.onetomany) {
            let res = null
            if (item.queryEvent) {
              res = this[item.queryEvent]()
            } else {
              let data = {
                tablename: item.tables[0],
                condition: `f_process_id='${this.selectdata.f_process_id}'`
              }
              res = await this.$resetpost(
                'rs/sql/applySingleTable',
                {data: data},
                {resolveMsg: null, rejectMsg: 'onetomany查询失败'}
              )
            }
            item.rows = res.data
            // 初始化onetomany中的fields
            for (const field of item.fields) {
              if (!field.value) {
                if (field.value !== 0) {
                  field.value = null
                }
              }

              if (field.default || field.default === 0) {
                field.value = field.default
              }

              // datepicker
              if (field.type === 'datepicker' && !field.value && field.default) {
                field.value = new Date().Format(`${field.format ? field.format : 'yyyy-MM-dd HH:mm:ss'}`)
              }

              if (field.type === 'select') {
                let temp = this.$appdata.getParam(field.label)

                if (temp && temp.length > 0) {
                  field.options = temp
                }

                if (field.paramLabel) {
                  temp = this.$appdata.getParam(field.paramLabel)
                  if (temp && temp.length > 0) {
                    item.options = temp
                  }
                }
              }
            }
          }
        }
        // 消除双向绑定，避免子组件（显示层）数据更改，父组件（控制层）也更改
        let temp = JSON.parse(JSON.stringify(this.selectdata))
        this.show_data = temp
        this.$nextTick(() => {
          this.showview = true
        })
        const defname = this.selectdata.defname
        const type = this.selectdata.f_apply_type
        const  title=this.selectdata.title
         if(title=='信息修改' ||title=='信息变更'){
           this.getCheckPay(this.selectdata.fields, defname, type)
         }
        if( type=='非民用报建'  && title=='费用调整'){
          if(defname=='报装缴费'){
            this.getCheckPayRecording()
            if(this.recording ==1){ //收费了
              this.modifData(this.selectdata.fields,0)
            }
            if(this.recording ==0){  //没收费
              this.modifData(this.selectdata.fields,1)
            }
          }
        }
      },
      // 金额转大写
      smalltoBIG(n) {
        let fraction = ['角', '分'];
        let digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
        let unit = [['元', '万', '亿'], ['', '拾', '佰', '仟']];
        let head = n < 0 ? '欠' : '';
        n = Math.abs(n);

        let s = '';

        for (var i = 0; i < fraction.length; i++) {
          s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
        }
        s = s || '整';
        n = Math.floor(n);

        for (var i = 0; i < unit[0].length && n > 0; i++) {
          let p = '';
          for (var j = 0; j < unit[1].length && n > 0; j++) {
            p = digit[n % 10] + unit[1][j] + p;
            n = Math.floor(n / 10);
          }
          s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
        }
        return head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整')
      },
      getLableValue(label) {
        for (const item of this.show_data.fields) {
          if (item.label === label && item.type !== 'number') {
            return item.value || ''
          }
          if (item.label === label && item.type === 'number') {
            return item.value || 0
          }
        }
      },
      getLableOptions(label) {
        for (const item of this.show_data.fields) {
          if (item.label === label) {
            return item.options
          }
        }
      },
      setLabelValue(label, value) {
        for (const item of this.show_data.fields) {
          if (item.label === label) {
            item.value = value
            this.show_data[item.field] = value
          }
        }
      },
      setLabelOptions(label, options) {
        for (const item of this.show_data.fields) {
          if (item.label === label) {
            item.options = options
          }
        }
      },
      showLabels(...labels) {
        for (const item of this.show_data.fields) {
          if (labels.includes(item.label)) {
            item.hidden = false
          }
        }
      },
      hideLabels(...labels) {
        for (const item of this.show_data.fields) {
          if (labels.includes(item.label)) {
            item.hidden = true
          }
        }
      },
      showButtons(...buttons) {
        for (const item of this.show_data.buttons) {
          if (buttons.includes(item.button_name)) {
            item.hidden = false
          }
        }
      },
      hideButtons(...buttons) {
        for (const item of this.show_data.buttons) {
          if (buttons.includes(item.button_name)) {
            item.hidden = true
          }
        }
      },
      requiredLabels(...labels) {
        for (const item of this.show_data.fields) {
          if (labels.includes(item.label)) {
            item.required = true
          }
        }
      },
      electiveLabels(...labels) {
        for (const item of this.show_data.fields) {
          if (labels.includes(item.label)) {
            item.required = false
          }
        }
      },
      readonlyLabels(...labels) {
        for (const item of this.show_data.fields) {
          if (labels.includes(item.label)) {
            item.readonly = true
            item.disabled = true
          }
        }
      },
      readwriteLabels(...labels) {
        for (const item of this.show_data.fields) {
          if (labels.includes(item.label)) {
            item.readonly = false
            item.disabled = false
          }
        }
      },
      disabledButtons(...buttons) {
        for (const item of this.show_data.buttons) {
          if (buttons.includes(item.button_name)) {
            item.disabled = true
          }
        }
      },
      enableButtons(...buttons) {
        for (const item of this.show_data.buttons) {
          if (buttons.includes(item.button_name)) {
            item.disabled = false
          }
        }
      },
      async checkDuplicate(index) {
        let http = new HttpResetClass()
        let data = {
          tablename: 't_apply',
          condition: `${this.show_data.fields[index].field} = '${this.show_data.fields[index].value}'`
        }
        let res = await http.load('POST', 'rs/sql/applySingleTable', {data: data}, {
          resolveMsg: null,
          rejectMsg: `${this.show_data.fields[index].label}查询失败`
        })
        if (res.data.length > 0) {
          this.show_data.fields[index].value = null
          this.$showMessage(`${this.show_data.fields[index].label}已存在！！！`)
        }
      }
    },
    events: {
      async 'stopApply' () {

        let data = {
          apply: this.show_data,
          user: this.$login.f
        }

        let res = await this.$resetpost(
          `rs/logic/stopApply`,
          {data: data},
          {resolveMsg: null, rejectMsg: '终止报建失败！！！'}
        )

        this.$dispatch('loadPage')
      },
      async 'pauseApply' () {

        let data = {
          apply: this.show_data,
          user: this.$login.f
        }

        let res = await this.$resetpost(
          `rs/logic/pauseApply`,
          {data: data},
          {resolveMsg: null, rejectMsg: '暂停报建失败！！！'}
        )

        this.$dispatch('loadPage')
      },
      async 'modifyInfo'() {
        if(this.selectdata.title === '费用修改'){
          let data = {
            tablename: 't_charge_record',
            condition: `f_process_id='${this.selectdata.f_process_id}'`
          }
          res = await this.$resetpost(
            'rs/sql/applySingleTable',
            {data: data},
            {resolveMsg: null, rejectMsg: '收费信息查看'}
          )
          if (res.data.length > 0){
            this.$showMessage('用户已缴费，无法修改！！！', ['confirm']).then((res) => {
              if (res === 'confirm') {
                this.$dispatch('loadPage')
              }
            })
            throw '用户已缴费，无法修改！！！'
          }else{
            let datas = {
              data: this.show_data,
              user: this.$login.f
            }
            let http = new HttpResetClass()
            let res = http.load('POST', 'rs/logic/modifyRecords', {data:datas}, {
              resolveMsg: null,
              rejectMsg: '保存修改记录失败！！！'
            })
          }
        }
        if(this.selectdata.title === '费用调整'){
          let data = {
            data: this.show_data,
            user: this.$login.f
          }
          let http = new HttpResetClass()
          let res = http.load('POST', 'rs/logic/modifyRecords', {data:data}, {
            resolveMsg: null,
            rejectMsg: '保存修改记录失败！！！'
          })
        }
        console.log("保存数据")
        let res = await this.$resetpost(
          `rs/entity/t_apply`,
          this.show_data,
          {resolveMsg: null, rejectMsg: '数据保存失败！！！'}
        )
        this.$dispatch('loadPage')
      },
      //身份证号码校验
      'checkIdnumber' (index) {
        if(this.show_data.f_credentials === '身份证'){
          var verify = /^[1-9]\d{5}(18|19|20|21)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
          if (!verify.test(this.show_data.fields[index].value)){
            this.show_data.fields[index].value = null
            this.$showMessage('身份证号码格式错误请重新输入！！！')
          }
        }
      },
      //电话号码校验
      'checkPhone' (index) {
        var verify = /^([1][0-9]{10})$/
        if (!verify.test(this.show_data.fields[index].value)){
          this.show_data.fields[index].value = null
          this.$showMessage('电话号码格式错误请重新输入！！！')
        }
      },
      'applyPaperChange' (index) {
        console.log("测试是否进入")
        if (this.show_data.f_paper_type === '专票') {
          this.requiredLabels('购货单位名称','购货单位识别号', '购货单位银行账号', '购货单位地址电话')
        }else {
          this.electiveLabels( '购货单位识别号', '购货单位银行账号', '购货单位地址电话')
        }
      },
      // 获取view层button事件
      async 'button' (){
        console.log("保存数据")
        let res = await this.$resetpost(
          `rs/entity/t_apply`,
          this.show_data,
          {resolveMsg: null, rejectMsg: '数据保存失败！！！'}
        )

        this.$dispatch('loadPage')
      },
      // 失去焦点出触发事件
      'onchange' (index) {
      },
      'onblur' (index) {},
      'oninput' (index) {},
      'initializtionView' () {},
      async 'onchangeModal' (index, fieldIndex) {
      },
      async 'onblurModal' (index, fieldIndex) {

      },
      async 'oninputModal' (index, fieldIndex) {

      },
      async 'onetomanydelete' (index, rowIndex) {

        let http = new HttpResetClass()

        let res = await http.load(
          'DELETE',
          `rs/entity/${this.show_data.onetomany[index].tables[0]}/${this.show_data.onetomany[index].rows[rowIndex].id}`,
          null,
          {resolveMsg: null, rejectMsg: '删除失败！！！'}
        )

        res = await this.$resetpost(
          'rs/entity/t_apply',
          this.show_data
        )

        this.$dispatch('breakControl', this.show_data)
      },
      async 'onetomanyupdate' (index, rowIndex) {
        let data = this.show_data.onetomany[index].rows[rowIndex]

        this.show_data.onetomany[index].fields.forEach(item => {
          data[item.field] = item.value
        })
        let res = await this.$resetpost(
          `rs/entity/${this.show_data.onetomany[index].tables[0]}`,
          data
        )

        res = await this.$resetpost(
          'rs/entity/t_apply',
          this.show_data
        )

        this.$dispatch('breakControl', this.show_data)
      },
      async 'onetomanyadd' (index) {
        let data = {
          f_process_id : this.show_data.f_process_id,
          f_operator_id: this.$login.f.id,
          f_operator: this.$login.f.name,
          f_operation_date: new Date().Format('yyyy-MM-dd HH:mm:ss'),
          f_orgid: this.$login.f.orgid,
          f_orgname: this.$login.f.orgs
        }
        this.show_data.onetomany[index].fields.forEach(item => {
          data[item.field] = item.value
        })
        let res = await this.$resetpost(
          `rs/entity/${this.show_data.onetomany[index].tables[0]}`,
          data
        )

        res = await this.$resetpost(
          'rs/entity/t_apply',
          this.show_data
        )

        this.$dispatch('breakControl', this.show_data)
      }
    },
    watch:{
      deep: true
    }
  }
</script>
