<template>
  <view>
    <cu-custom bgColor="bg-gradual-blueness" :isBack="true">
      <block slot="backText">返回</block>
      <block slot="content">项目主管部门负责人待审批</block>
    </cu-custom>
    <view class="form">
      <view class="wui-form-list">
        <view class="cu-form-group">
          <view class="title">特级动火申请</view>
        </view>
        <view class="cu-form-group">
          <view class="title">申请办理人：</view>
          {{ form.APPLY_USER_NAME }}
        </view>
        <view class="cu-form-group">
          <view class="title">申请日期：</view>
          {{ form.APPLICATION_DATE }}
        </view>
        <view class="cu-form-group">
          <view class="title">作业编号：</view>
          {{form.JOB_NUMBER}}
        </view>
        <view class="cu-form-group">
          <view class="title">作业类型：</view>
          {{ form.JOB_TYPE_NAME }}
        </view>
        <view class="cu-form-group">
          <view class="title">动火许可证：</view>
          <button class="cu-btn bg-blue margin-tb-sm lg" @click="goToDelay()">查看</button>
        </view>
      </view>
      <view class="wui-form-list">
        <view class="cu-form-group">
          <view class="title">动火单位作业负责人确认</view>
        </view>
        <view class="cu-form-group">
          <view class="title">动火单位作业负责人：</view>
          {{ form.projectCompetent_USER_NAME }}
        </view>
        <view class="cu-form-group">
          <view class="title">确认时间：</view>
          {{ form.projectCompetent_OPERATTIME }}
        </view>

        <view class="cu-form-group">
          <view class="title">是否通过：</view>
          {{form.projectCompetent_TYPE =='2'?'通过':'不通过'}}
        </view>
      </view>
      <view class="wui-form-list">
        <view class="cu-form-group">
          <view class="title">项目主管人员初审</view>
        </view>
        <view class="cu-form-group">
          <view class="title">动火单位作业负责人：</view>
          {{ form.projectSupervisor_USER_NAME }}
        </view>
        <view class="cu-form-group">
          <view class="title">确认时间：</view>
          {{ form.projectCompetent_OPERATTIME }}
        </view>

        <view class="cu-form-group">
          <view class="title">是否通过：</view>
          {{form.projectSupervisor_TYPE =='2'?'通过':'不通过'}}
        </view>
      </view>

      <view class="wui-form-list">
        <view class="cu-form-group">
          <view class="title">项目主管部门负责人审核</view>
        </view>
        <view class="cu-form-group ">
          <view class="title text-hui">初审结果：</view>
          <radio-group class="selected"  @change="radioType" :disabled="forbidEdit">
            <view class="group mr20">
              <radio class='radio' :disabled="forbidEdit" value="2" :checked="form.TYPE==2"></radio>
              <text>通 过</text>
            </view>
            <view class="group">
              <radio class='radio' :disabled="forbidEdit" value="1" :checked="form.TYPE==1"></radio>
              <text>不通过</text>
            </view>
          </radio-group>
        </view>
        <div v-if="form.TYPE ==2">
          <view class="cu-form-group" @click="modalShow = true">
            <view class="title">签字：</view>
            <image style="width: 150px;height: 50px" v-if="signImgList.length>0" :src="signImgList[0].filePath" mode="aspectFill"></image>
            <button class="cu-btn bg-green shadow" @tap="modalShow = true" data-target="Modal">手写签字</button>
          </view>
          <view class="cu-form-group">
            <view class="title">签字时间：</view>
            {{todayDate}}
          </view>
          <view class="cu-bar bg-white margin-top">
            <view class="action">
              上传会签文件
            </view>
            <view class="action">
              {{meetingImgList.length}}/4
            </view>
          </view>
          <view class="cu-form-group">
            <view class="grid col-4 grid-square flex-sub">
              <view class="bg-img" v-for="(item,index) in meetingImgList" :key="index" @tap="ViewImage($event,'meetingImgList')" data-type="0"
                    :data-url="meetingImgList[index].filePath">
                <image :src="meetingImgList[index].filePath" mode="aspectFill"></image>
                <view class="cu-tag bg-red" @tap.stop="DelImg($event,'meetingImgList')" data-type="0" :data-index="index">
                  <text class='cuIcon-close'></text>
                </view>
              </view>
              <view class="solids" @tap="ChooseImage(0)" v-if="meetingImgList.length<4">
                <text class='cuIcon-cameraadd'></text>
              </view>
            </view>
          </view>
          <view class="cu-bar bg-white margin-top">
            <view class="action">
              上传附件
            </view>
            <view class="action">
              {{appendixImgList.length}}/4
            </view>
          </view>
          <view class="cu-form-group">
            <view class="grid col-4 grid-square flex-sub">
              <view class="bg-img" v-for="(item,index) in appendixImgList" :key="index" @tap="ViewImage($event,'appendixImgList')" data-type="0"
                    :data-url="appendixImgList[index].filePath">
                <image :src="appendixImgList[index].filePath" mode="aspectFill"></image>
                <view class="cu-tag bg-red" @tap.stop="DelImg($event,'appendixImgList')" data-type="0" :data-index="index">
                  <text class='cuIcon-close'></text>
                </view>
              </view>
              <view class="solids" @tap="ChooseImage2(0)" v-if="appendixImgList.length<4">
                <text class='cuIcon-cameraadd'></text>
              </view>
            </view>
          </view>
          <view class="cu-form-group">
            <view class="title">分公司安全总监部门：</view>
            <block v-if="!forbidEdit">
              <view class="picker-tree-box">
                <view class="picker-tree" @tap="showZgTree('tkiTree6')">
                  {{ form.inspectorGeneral_DEPT_NAME || '请选择' }}
                </view>
              </view>
              <tki-tree ref="tkiTree6" :selectParent=true :range="treeNode" rangeKey="name" @confirm="zgtreeConfirm($event,'inspectorGeneralList')"
                        @cancel="zgtreeCancel"></tki-tree>
            </block>
            <block v-else>{{ form.inspectorGeneral_DEPT_NAME }}</block>
          </view>
          <view class="cu-form-group" v-if="form.inspectorGeneral_DEPT_NAME">
            <view class="title">分公司安全总监负责人：</view>
            <picker @change="projectChange" :disabled="forbidEdit" :value="form.inspectorGeneral_INDEX"
                    :range="inspectorGeneralList" range-key="NAME">
              <view class="picker">
                {{ form.inspectorGeneral_USER_NAME || '请选择' }}
              </view>
            </picker>
          </view>
          <view class="cu-form-group" v-if="form.inspectorGeneral_PHONE">
            <view class="title">分公司安全总监负责人电话：</view>
            {{ form.inspectorGeneral_PHONE }}
          </view>
        </div>
      </view>
    </view>

    <view class="cu-bar btn-group" style="margin-top: 30upx;">
      <button v-if="!forbidEdit" class="cu-btn bg-blue margin-tb-sm lg" @click="goSubmit('1')">提交</button>
      <button v-if="forbidEdit" class="cu-btn bg-green margin-tb-sm lg" @click="$noMultipleClicks(goback)">返回</button>
    </view>
    <view class="padding flex flex-direction"></view>
    <view :class="['cu-modal',{'show':modalShow}]">
      <sign @confirm="subCanvas" @cancel="modalShow = false"></sign>
    </view>
  </view>
</template>

<script>
  import {
    basePath,
    loginUserId,
    loginSession,
    corpinfoId,
    baseImgPath,
    formatDate
  } from '@/common/tool.js';
  import sign from '@/components/sign/sign.vue';
  import tkiTree from "@/components/select-tree/select-tree.vue"

  export default {
    components: {
      sign,
      tkiTree
    },
    data() {
      return {
        baseImgPath,
        forbidEdit: false,
        form: {
          TYPE:'1',
          HOTWORKAPPLICATION_ID: '',
          inspectorGeneral_DEPT_ID:'',
          inspectorGeneral_DEPT_NAME:'',
          inspectorGeneral_USER_ID:'',
          inspectorGeneral_USER_NAME:'',
          inspectorGeneral_PHONE:'',
          inspectorGeneral_INDEX:'',
        },
        treeNode: [],
        inspectorGeneralList:[],
        todayDate:'',
        signImgList:[],
        meetingImgList:[],
        appendixImgList:[],
        modalShow: false,

      }
    },
    onLoad(event) {
      this.form.HOTWORKAPPLICATION_ID = event.id
      this.todayDate =  formatDate(new Date(), 'yyyy-MM-dd hh:mm');
      this.getData();
      loginSession();
      this.getDept();
    },
    methods: {
      getData() {
        var _this = this;
        uni.showLoading({
          title: '请稍候'
        })
        uni.request({
          url: basePath + '/app/hotworkapplication/goEdit',
          method: 'POST',
          header: {
            'Content-type': 'application/x-www-form-urlencoded'
          },
          data: {
            HOTWORKAPPLICATION_ID: _this.form.HOTWORKAPPLICATION_ID,
          },
          success: (res) => {
            if ("success" == res.data.result) {
              this.form = res.data.pd;
              this.form.inspectorGeneral_DEPT_NAME = ''
              this.form.inspectorGeneral_USER_NAME = ''
              this.form.inspectorGeneral_PHONE = ''
              this.form.TYPE = '1'
              let HOT_WORK_OPERATOR_NAME = res.data.pd.HOT_WORK_OPERATOR_NAME
              this.form.HOT_WORK_OPERATOR_NAME = HOT_WORK_OPERATOR_NAME.substring(0, HOT_WORK_OPERATOR_NAME.length - 1).split(',');
              uni.hideLoading();
            } else if ("exception" == res.data.result) {
              uni.showToast({
                title: '错误',
                duration: 2000
              });
            }
          }
        });
      },
      getDept(){
        let _this = this;
        uni.request({
          url: basePath + '/app/sys/listTree', //部门下拉接口
          method: 'POST',
          dataType: 'json',
          header: {
            'Content-type': 'application/x-www-form-urlencoded'
          },
          data: {
            CORPINFO_ID: corpinfoId,
          },
          success: (res) => {
            if ("success" == res.data.result) {
              _this.treeNode = eval(res.data.zTreeNodes);
            } else {
              uni.showToast({
                title: res.data.message,
                duration: 2000
              });
            }
          }
        });
      },
      showZgTree(ref) {
        this.$refs[ref]._show();
      },
      zgtreeCancel(e) {
        this.isUps = false;
      },
      zgtreeConfirm(e,list) {
        if (list === "inspectorGeneralList") {
          this.form.inspectorGeneral_DEPT_ID= e[0].id;
          this.form.inspectorGeneral_DEPT_NAME= e[0].name;
          this.form.inspectorGeneral_USER_ID= '';
          this.form.inspectorGeneral_USER_NAME= '';
          this.form.inspectorGeneral_INDEX= '';
          this.$forceUpdate();
        }
        this.getUserList(list,e[0].id);
      },
      getUserList(list,DEPARTMENT_ID) {
        //发送 post 请求
        var _this = this;
        uni.request({
          method: 'POST',
          dataType: 'json',
          header: {
            'Content-type': 'application/x-www-form-urlencoded'
          },
          url: basePath + '/app/sys/listUser',
          data: {
            DEPARTMENT_ID, NOMAIN:'1',
            tm: new Date().getTime()
          },
          success: function (res) {
            if ("success" == res.data.result) {
              _this[list] = res.data.userList;
            } else {
              uni.showToast({
                title: res.data.message,
                duration: 2000
              });
            }
          }
        })
      },
      projectChange(e){
        this.form.inspectorGeneral_INDEX = e.detail.value;
        this.form.inspectorGeneral_USER_ID = this.inspectorGeneralList[e.detail.value].USER_ID;
        this.form.inspectorGeneral_USER_NAME = this.inspectorGeneralList[e.detail.value].NAME;
        this.form.inspectorGeneral_PHONE = this.inspectorGeneralList[e.detail.value].USERNAME;
        this.$forceUpdate();
      },
      goToDelay(id) {
        uni.navigateTo({
          url: '/pages/application/eight-assignments/super-hotwork/detail?id=' + this.form.HOTWORKAPPLICATION_ID
        });
      },
      radioType(e){
        this.form.TYPE = e.detail.value
        this.$forceUpdate();
      },

      goSubmit(STATUS) {
        var _this = this;
        let required = true
        if (STATUS == 1) {
          if (this.form.TYPE == 2) {
            console.info('this.signImgList')
            console.info(this.signImgList)
            if (this.signImgList.length == 0) {
              uni.showToast({
                icon: 'none',
                title: '请签字',
                duration: 1500
              });
              required = false
            }
            if (this.meetingImgList.length == 0) {
              uni.showToast({
                icon: 'none',
                title: '请上传会签文件',
                duration: 1500
              });
              required = false
            }
            if (this.appendixImgList.length  == 0) {
              uni.showToast({
                icon: 'none',
                title: '请上传附件',
                duration: 1500
              });
              required = false
            }
            if (!this.form.inspectorGeneral_USER_ID) {
              uni.showToast({
                icon: 'none',
                title: '请选择分公司安全总监负责人',
                duration: 1500
              });
              required = false
            }
          }
          if (!required) {
            return
          }
        }
        uni.showLoading({
          title: '请稍候'
        })
        var fileList = [];
        for (var i = 0; i < _this.meetingImgList.length; i++) {
          if(!_this.meetingImgList[i].id){
            var file = {};
            file.type = 203;
            file.filePath = _this.meetingImgList[i].filePath;
            fileList.push(file);
          }
        }
        for (var i = 0; i < _this.appendixImgList.length; i++) {
          if(!_this.appendixImgList[i].id){
            var file = {};
            file.type = 204;
            file.filePath = _this.appendixImgList[i].filePath;
            fileList.push(file);
          }
        }
        new Promise((resolve, reject) => {
          _this.submit().then(() => {resolve();})
          for (var i =0;i<fileList.length ;i++){
            _this.uploadImg(fileList,i).then(() => {resolve();})
          }
        }).then(() => {
          var i=0;
        }).then(() => {
          uni.showToast({
            icon:'none',
            title: '保存成功',
            duration: 2000
          });
          var pages = getCurrentPages();	// 获取当前页面栈
          var prePage = pages[pages.length - 2];	// 上一个页面
          // var task = prePage.$vm.list[_this.index];
          if(_this.index) {
            prePage.$vm.initflag = true;    // A 页面 init方法 为true
            // prePage.$vm.list[_this.index].ISNORMAL = 1;
            // prePage.$vm.list[_this.index].HIDDEN_ID = _this.pd.HIDDEN_ID;
          }
          uni.navigateBack({});
          uni.hideLoading();
        })
      },

      submit() {
        var _this = this;
        return new Promise((resolve, reject) => {
          uni.uploadFile({
            url: basePath + "/app/hotworkapplication/editOpinion",
            filePath: _this.signImgList.length == 1?_this.signImgList[0].filePath:'',
            name: 'FFILE',
            formData: {
              ...this.form,
              CORPINFO_ID: corpinfoId,
              loginUserId:loginUserId
            },
            success: (res) => {
              uni.hideLoading();
              var resJson = JSON.parse(res.data)
              if(resJson.result =='success'){
                uni.showToast({
                  icon: 'none',
                  title: '保存成功',
                  duration: 2000
                });
                _this.goback()
              }else{
                uni.showToast({
                  icon: 'none',
                  title: resJson.msg,
                  duration: 1500,

                });
                setTimeout(function () {
                  _this.goback()
                }, 1500);
              }
            }
          });
        })
      },
      uploadImg(tempFilePaths,i){
        return new Promise((resolve, reject) => {
          var _this = this;
          if(tempFilePaths.length==0){
            resolve();
          }
          uni.showLoading({
            title: '上传中'
          })
          uni.uploadFile({
            url: basePath+'/app/imgfiles/add',
            filePath: tempFilePaths[i].filePath,
            name: 'FFILE',
            formData: {
              'TYPE': tempFilePaths[i].type,
              'FOREIGN_KEY': _this.form.HOTWORKAPPLICATION_ID
            },
            success: (res) => {

            },
            fail: (err) => {
              uni.hideLoading();
              uni.showModal({
                content: err.errMsg,
                showCancel: false
              });
            }
          })
        })
      },
      subCanvas(e) {
        this.signImgList =[]
        this.signImgList.push(e);
        this.modalShow = false;
      },
      ViewImage(e,listName) {
        if(e.currentTarget.dataset.type==0) {
          let files =[];
          for(var i=0;i<this[listName].length;i++){
            files.push(this[listName][i].filePath)
          }
          uni.previewImage({
            urls: files,
            current: e.currentTarget.dataset.url
          });
        }else{
          let files =[];
          for(var i=0;i<this[listName].length;i++){
            files.push(this[listName][i].filePath)
          }
          uni.previewImage({
            urls: files,
            current: e.currentTarget.dataset.url
          });
        }
      },
      DelImg(e,listName){
        var _this = this;
        let i = e.currentTarget.dataset.index
        _this[listName].splice(i, 1)
      },
      //图片上传
      ChooseImage(e) {
        var _this = this;
        var ss = 4 - this.meetingImgList.length;
        uni.chooseImage({
          count: ss, //默认9
          sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
          sourceType: ['camera', 'album'], //从相册选择
          success: (res) => {
            for (let i = 0; i < res.tempFilePaths.length; i++) {
              if (e == 0) {
                let img = {};
                img.id = '';
                img.filePath = res.tempFilePaths[i];
                this.meetingImgList.push(img)
              } else {
                let img = {};
                img.id = '';
                img.filePath = res.tempFilePaths[i];
                this.meetingImgList.push(img)
              }
            }
          }
        });
      },
      //图片上传
      ChooseImage2(e) {
        var _this = this;
        var ss = 4 - this.appendixImgList.length;
        uni.chooseImage({
          count: ss, //默认9
          sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
          sourceType: ['camera', 'album'], //从相册选择
          success: (res) => {
            for (let i = 0; i < res.tempFilePaths.length; i++) {
              if (e == 0) {
                let img = {};
                img.id = '';
                img.filePath = res.tempFilePaths[i];
                this.appendixImgList.push(img)
              } else {
                let img = {};
                img.id = '';
                img.filePath = res.tempFilePaths[i];
                this.appendixImgList.push(img)
              }
            }

          }
        });
      },
      goback() {
        uni.navigateBack({
          delta: 1
        });
        uni.hideLoading();
      },
    }
  }
</script>

<style>
  .right_icon {
    position: relative;
    padding-right: 36upx;
    width: 200upx;
    text-align: right;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  .right_icon ::after {
    font-family: cuIcon;
    display: block;
    content: "\e6a3";
    position: absolute;
    font-size: 17px;
    color: #8799a3;
    line-height: 50px;
    width: 30px;
    text-align: center;
    top: -28upx;
    bottom: 0;
    right: -22upx;
    margin: auto;
  }

  .modal_content {
    display: flex;
    text-align: left;
  }
  .modal_left {
    flex-basis: 50%;
    padding: 50upx 20upx;
    border-right: 1px solid #000000;
  }
  .modal_right {
    flex-basis: 50%;
    padding: 50upx;
  }
  .modal_left_title,.modal_right_title{
    font-size: 16px;
    color: #000000;
    font-weight: 700;
  }
  .checkbox-item{
    display: flex;
    align-items:center;
    padding: 0 30upx;
    min-height: 100upx;
    background-color: #ffffff;
    border-bottom: 1upx solid #ddd;
  }
  .checkbox-item:last-child{
    border-bottom: none;
  }
  .selected{
    display: flex;
    align-items: center;
    height: 100upx;
  }
  .selected .radio{
    transform:scale(0.8);
    margin-right: 10upx;
  }
</style>
