<template>
  <div class="auto clearfix">
    <show-back-reason :selectdata="show_data"></show-back-reason>
  </div>
  <service-view v-ref:service_show :data="show_data" v-if="showview"></service-view>
</template>
<script>
  import Vue from 'vue'
  import {HttpResetClass} from 'vue-client'
  import {isEmpty} from "../../../Util";
  // Date格式化
  Date.prototype.Format = function (fmt) {
    var o = {
      'M+': this.getMonth() + 1, // 月份
      'd+': this.getDate(), // 日
      'H+': this.getHours(), // 小时
      'm+': this.getMinutes(), // 分
      's+': this.getSeconds(), // 秒
      'q+': Math.floor((this.getMonth() + 3) / 3), // 季度
      'S': this.getMilliseconds() // 毫秒
    }
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length))
    for (var k in o) {
      if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
    }
    return fmt
  }
  export default {
    title: '报建监控控制层',
    props: {
      selectdata: {
        type: Object
      },
      nodeSnapshot: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        data: null,    // 展示的数据
        json_datas: null, // json配置数据结构
        showview: false, // 控制显示层显示
        show_data: null
      }
    },
    created () {
      this.refurbish()
    },
    methods: {
      // 初始化模块
      async refurbish() {
        this.json_datas = this.$workflow_vue
        let sum = 0
        let jsonData = {}
        if (!this.json_datas || !this.json_datas.activitys || this.json_datas.activitys.length === 0) {
          this.$showMessage("网络故障，请刷新页面")
          return
        }
        this.json_datas.activitys.forEach(item => {
          if (this.selectdata.defname === item.title) {
            jsonData = item  // 拿到当前节点的json配置信息
            sum++ // 节点名一样的个数
          }
          return this.selectdata.defname === item.title // 拿到当前节点的json配置信息
        })
        if (sum === 0) {
          this.$showMessage(`没有在JSON配置文件中找到活动名为:(${this.selectdata.defname})的节点配置`)
          return
        }
        if (sum > 1) {
          this.$showMessage(`在JSON配置文件中找到活动名为:(${this.selectdata.defname})的节点配置:${sum}个`)
          return
        }

        this.data = null
        this.data = jsonData
        this.data = Object.assign({}, this.data, this.selectdata)

        // fields 字段填充值
        for (const item of this.data.fields) {
          if (this.selectdata[item.field]) {
            item.value = this.selectdata[item.field]
          }
          if (this.selectdata[item.field] === 0) {
            item.value = 0
          }
          item.readonly = true
          item.disabled = true
          if (item.logo) {
            if (item.ready) {
              item.options = await this[item.ready]()
            }
          }
          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 (this.data.components) {
          this.data.components.forEach(item => {
            item.mark = 1
          })
        }

        // onetomany 数据获取
        if (this.data.onetomany) {
          for (const item of this.data.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

            // 隐藏所有操作
            item.hiddenOperate = true
          }
        }

        // 去除button
        this.data.buttons = null

        // 完成时间和完成人,部门，分公司
        if (this.selectdata.state === '结束') {
          this.data.operate_date = new Date(this.selectdata.finishtime).Format('yyyy-MM-dd')
          this.data.operator = this.selectdata.person

          let http = new HttpResetClass()
          try {
            let res = await http.load('POST', 'rs/search', {
              source: 'this.getInfo()',
              userid: this.selectdata.userid
            }, {resolveMsg: null, rejectMsg: null})
            let user = res.data
            this.data.orgs = user.orgs
            this.data.parentname = user.deps
          } catch (e) {
            this.data.orgs = "榆林."+this.$login.f.orgs
            this.data.parentname = this.$login.f.deps
          }
        }
          if (this.selectdata.f_apply_nature === '散户') {
            this.hideLabels('营业执照', '小区')
            this.electiveLabels('营业执照', '购货单位识别号', '购货单位银行账号', '购货单位地址电话', '小区')
          }
          if (this.selectdata.f_apply_nature === '小区') {
            this.showLabels('营业执照', '小区', '小区名称')
            this.requiredLabels( '小区')
          }
        if (this.selectdata.f_dispatching_type === '施工工队') {
          this.showLabels('现场项目负责人', '安装单位', '建设单位', '监理单位', '土建单位', '检测单位')
          this.requiredLabels( '小区')
        }
        // 消除双向绑定，避免子组件（显示层）数据更改，父组件（控制层）也更改
        let temp = JSON.parse(JSON.stringify(this.data))

        this.show_data = temp
        this.$nextTick(() => {
          if ((this.show_data.defname==='报装缴费' || this.show_data.defname==='收费标准') && !(this.$login.f.rolesnames.includes('营业厅报装')||this.$login.f.rolesnames.includes('市场部报装'))){
            this.showview = false
            this.$showMessage("对不起，您没有查看此节点的权限！")
          }else {
            this.showview = true
          }
        })
      },
      // json配置数据处理
      async initializtion() {
        // 查询是否有当前节点快照信息,如果有使用快照数据，没有则展示最新数据
        if (this.nodeSnapshot && this.data.nodeSnapshot) {
          let http = new HttpResetClass()
          let data = {
            tablename: 't_node_snapshot',
            condition: `actid = '${this.selectdata.actid}' and f_process_id='${this.selectdata.f_process_id}'`
          }
          let res = await http.load('POST', 'rs/sql/applySingleTable', {data: data}, {
            resolveMsg: null,
            rejectMsg: null
          })
          if (res.data.length > 0) {
            data = JSON.parse(res.data[0].f_node_data)

            this.data.fields = data.fields
            this.data.onetomany = data.onetomany
            this.data.title = data.title
          }
        }
      },
      hideLabels(...labels) {
        console.log('报建性质1')
        for (const item of this.data.fields) {
          if (labels.includes(item.label)) {
            item.hidden = true
          }
        }
      },
      electiveLabels(...labels) {
        console.log('报建性质2')
        for (const item of this.data.fields) {
          if (labels.includes(item.label)) {
            item.required = false
          }
        }
      },
      showLabels(...labels) {
        console.log('报建性质3')
        for (const item of this.data.fields) {
          if (labels.includes(item.label)) {
            item.hidden = false
          }
        }
      },
      requiredLabels(...labels) {
        console.log('报建性质4')
        for (const item of this.data.fields) {
          if (labels.includes(item.label)) {
            item.required = true
          }
        }
      },
      setLabelOptions(label, options) {
        for (const item of this.show_data.fields) {
          if (item.label === label) {
            item.options = options
          }
        }
      },
      // 获取小区
      async getResidentialArea () {
        let data = {
          tablename: 't_area_address',
          condition: `f_filiale like '%${"榆林."+this.$login.f.orgs}%' and f_area_status = '启用'`
        }
        let http = new HttpResetClass()
        let res = await http.load(
          'POST',
          `rs/sql/applySingleTable`,
          {data: data},
          {resolveMsg: null, rejectMsg: '小区查询失败！！！'}
        )
        return res.data.map(item => {
          return {
            label: item.f_residential_area,
            value: item.id
          }
        })
      },
      // 获取气表品牌
      async getMeterBrand () {
        let data = {
        }

        let http = new HttpResetClass()
        let res = await http.load(
          'POST',
          `rs/sql/getMeterBrand1`,
          {data: data},
          {resolveMsg: null, rejectMsg: '气表品牌查询失败！！！'}
        )

        return res.data
      },
      async meterBrandChenge (index) {
        if (isEmpty(this.selectdata.f_meter_brand)) {
          console.log("测试无表具")
          return
        }
        let data = {
          f_gasbrand_id: this.selectdata.f_meter_brand
        }
        let http = new HttpResetClass()
        let res = await http.load(
          'POST',
          `rs/sql/getGasModel`,
          {data: data},
          {resolveMsg: null, rejectMsg: '气表型号查询失败！！！'}
        )
        console.log("测试有表具",res.data)
        return res.data
      },
      async getUserName() {
        console.log('用户姓名查询')
        if(this.selectdata.f_construction_unit_id){
          let data = {
            tablename: 't_user',
            condition: `id='${this.selectdata.f_construction_unit_id}'`
          }
          let res = await this.$resetpost(
            'rs/sql/applySingleTable',
            {data: data},
            {resolveMsg: null, rejectMsg: null}
          )
          return res.data.map(item => {
            return {
              label: item.name,
              value: item.id
            }
          })
        }
        return
      },
      async getConstructionWorker(){
        let data = {
          source: 'this.getParentByType($organization$).getChildByName($建设单位$).getChildren()',
          userid: this.$login.f.id
        }

        let res = await this.$resetpost(
          `rs/search`,
          {data: data},
          {resolveMsg: null, rejectMsg: '现场负责人查询失败！！！'}
        )

        return res.data.map(item => {
          return {
            label: item.name,
            value: item.id
          }
        })
      },
      // 安装单位签字人
      async getConstructionUnitId () {
        if (this.selectdata.f_construction_unit_id){
          let data = {
            tablename: 't_user',
            condition: `id='${this.selectdata.f_construction_unit_id}'`
          }
          let res = await this.$resetpost(
            'rs/sql/applySingleTable',
            {data: data},
            {resolveMsg: null, rejectMsg: null}
          )
          return res.data.map(item => {
            return {
              label: item.name,
              value: item.id
            }
          })
        }
      },
      // 安装单位负责人
      async getConstructionUnit () {
        let data = {
          source: 'this.getParentByType($organization$).getChildByName($工程施工队$).getChildren()',
          userid: this.$login.f.id
        }

        let res = await this.$resetpost(
          'rs/search',
          {data: data},
          {resolveMsg: null, rejectMsg: '安装单位负责人查询失败！！！'}
        )

        return res.data.map(item => {
          return {
            label: item.name,
            value: item.id
          }
        })
      },
      // 建设单位
      async getConstructOperator () {
        let data = {
          source: 'this.getParentByType($organization$).getChildByName($建设单位$).getChildren()',
          userid: this.$login.f.id
        }

        let res = await this.$resetpost(
          'rs/search',
          {data: data},
          {resolveMsg: null, rejectMsg: '建设单位人员查询失败！！！'}
        )

        return res.data.map(item => {
          return {
            label: item.name,
            value: item.id
          }
        })
      },
      // 监理单位
      async getSupervisorOperator () {
        let data = {
          source: 'this.getParentByType($organization$).getChildByName($监理单位$).getChildren()',
          userid: this.$login.f.id
        }

        let res = await this.$resetpost(
          'rs/search',
          {data: data},
          {resolveMsg: null, rejectMsg: '监理单位人员查询失败！！！'}
        )
        return res.data.map(item => {
          return {
            label: item.name,
            value: item.id
          }
        })
      },
      // 监理现场负责人
      async getSupervisorOperatorId () {
        let data = {
          source: 'this.getParentByType($organization$).getChildByName($监理班组$).getChildren()',
          userid: this.$login.f.id
        }
        let res = await this.$resetpost(
          'rs/search',
          {data: data},
          {resolveMsg: null, rejectMsg: '监理单位人员查询失败！！！'}
        )
        return res.data.map(item => {
          return {
            label: item.name,
            value: item.id
          }
        })
      },
      // 土建单位
      async getEngineeringOperator () {
        let data = {
          source: 'this.getParentByType($organization$).getChildByName($土建单位$).getChildren()',
          userid: this.$login.f.id
        }

        let res = await this.$resetpost(
          'rs/search',
          {data: data},
          {resolveMsg: null, rejectMsg: '土建单位人员查询失败！！！'}
        )
        let result = res.data.map(item => {
          return {
            label: item.name,
            value: item.id
          }
        })
        result.push({label:'用户自理',value:'用户自理'})
        result.push({label:'无',value:'无'})
        return result
      },
      // 检测单位
      async getCheckOperator () {
        let data = {
          source: 'this.getParentByType($organization$).getChildByName($检测单位$).getChildren()',
          userid: this.$login.f.id
        }

        let res = await this.$resetpost(
          'rs/search',
          {data: data},
          {resolveMsg: null, rejectMsg: '检测单位人员查询失败！！！'}
        )

        let result = res.data.map(item => {
          return {
            label: item.name,
            value: item.id
          }
        })
        result.push({label:'无',value:'无'})
        return result
      },
      // 户内出单日期
      async getOutdoorsTime () {
        for (const item of this.data.fields) {
          if (item.label === '户内出单日期') {
            item.value = this.data.f_release_date
            this.data[item.field] = item.value
          }else if(item.label === '庭院出单日期'){
            item.value = this.data.f_release_date
            this.data[item.field] = item.value
          }
        }
      },
      async getChargeDate() {
        let data = {
          tablename: 'activityins',
          condition: `processid = '${this.data.f_process_id}' and defname = '报装缴费'`,
        }

        let http = new HttpResetClass()
        let res = await http.load(
          'POST',
          `rs/sql/applySingleTable`,
          {data: data},
          {resolveMsg: null, rejectMsg: null}
        )
        if (res.data[0]){
          for (const item of this.data.fields) {
            if (item.label === '缴费日期') {
              item.value = res.data[0].finishtime
              this.data[item.field] = item.value
            }
          }
        }
      },
      async getSingAct() {
        let data = {
          f_process_id: this.data.f_process_id
        }
        let http = new HttpResetClass()
        let res = await http.load(
          'POST',
          `rs/sql/getSingAct`,
          {data: data},
          {resolveMsg: null, rejectMsg: '签字状态查询失败！！！'}
        )
        if (res.data.length > 0) {
          for (const item of this.data.fields) {
            if (item.label === '签字所在环节') {
              item.value = res.data[0].defname
              this.data[item.field] = item.value
            }
          }
        }
      }
    },
    events:{
      // 工程派工初始化
      async 'dispatchReadyEvent' () {
        console.log("cscc")
        if (isEmpty(this.show_data.f_meter_brand)) {
          return
        }
        let data = {
          f_gasbrand_id: this.show_data.f_meter_brand
        }
        let http = new HttpResetClass()
        let res = await http.load(
          'POST',
          `rs/sql/getGasModel`,
          {data: data},
          {resolveMsg: null, rejectMsg: '气表型号查询失败！！！'}
        )

        this.setLabelOptions('气表型号', res.data)
      },
      async 'buildReadyEvent' () {
        console.log("cscc")
        if (isEmpty(this.show_data.f_meter_brand)) {
          return
        }
        let data = {
          f_gasbrand_id: this.show_data.f_meter_brand
        }
        let http = new HttpResetClass()
        let res = await http.load(
          'POST',
          `rs/sql/getGasModel`,
          {data: data},
          {resolveMsg: null, rejectMsg: '气表型号查询失败！！！'}
        )

        this.setLabelOptions('气表型号', res.data)
      }
    },
    watch: {
      deep: true
    }
  }
</script>
<style scoped>
  /*清除model中的浮动*/
  .clearfix:after,.clearfix:before{
    display: table;
  }
  .clearfix:after{
    clear: both;
  }
</style>
