<template>
  <view>
    <cu-custom bgColor="bg-gradual-blueness" :isBack="true">
      <block slot="backText">返回</block>
      <block slot="content">监护人签字确认</block>
    </cu-custom>
    <scroll-view scroll-y="false">
      <view class="form">

        <detail v-if="pd.ELECTRICITY_ID" :electricityId="pd.ELECTRICITY_ID"></detail>

        <view class="wui-form-list">
          <view class="wui-sign" v-if="!files.length">
            <view class="title">监护人</view>
            <view>
              <view>
                <button class="cu-btn bg-green shadow" @tap="showModal">新增手写签字</button>
              </view>
            </view>
          </view>

          <view class="wui-sign-box wui-sign-box1" v-show="imgList && imgList.length > 0">
            <view class="sign-title">
              签字照片：
            </view>
            <view class="wui-sign-cotent">
              <view class="sign-img" v-for="(item,index) in imgList" :key="index" @tap="ViewImage" data-type="0"
                    :data-url="imgList[index].filePath">
                <image :src="imgList[index].filePath" mode="aspectFit"></image>
                <view class="cu-tag bg-red" @tap.stop="DelImg(index)">
                  <text class='cuIcon-close'></text>
                </view>
              </view>
            </view>
          </view>
          <view class="cu-modal" :class="modalName=='Modal'?'show':''">
            <writing-board :signShow="modalName =='Modal'" @confirm="subCanvas" @cancel="hideModal"/>
          </view>
        </view>
      </view>
      <view class="cu-bar btn-group" style="margin-top: 30upx;">
        <button class="cu-btn bg-red margin-tb-sm lg" @click="$noMultipleClicks(goSubmit(-1))">作废</button>
        <button class="cu-btn bg-green margin-tb-sm lg" @click="$noMultipleClicks(goSubmit(1))">通过</button>
      </view>
      <view class="padding flex flex-direction">
      </view>
    </scroll-view>
  </view>
</template>

<script>
import {
  basePath, corpinfoId, deptId, loginUser, formatDate, loginSession, baseImgPath
} from '@/common/tool.js';
import tkiTree from "@/components/select-tree/select-tree.vue"
import writingBoard from "@/components/horizontal-writing-board/writing-board.vue"
import gcoord from '@/common/gcoord.js'
import ruiDatePicker from '@/components/rattenking-dtpicker/rattenking-dtpicker.vue';
import detail from '@/pages/application/electricity/electricity-detail/index'

export default {
  components: {
    tkiTree, ruiDatePicker, writingBoard, detail
  },
  data() {
    return {
      baseImgPath: baseImgPath,
      isUps: false,
      forbidEdit: true,// 禁止修改
      msg: 'add',
      files: [],
      noClick: true,
      treeNode: [],//部门下拉数据
      levelList: [
        {id: '特级', name: '特级'},
        {id: '一级', name: '一级'},
        {id: '二级', name: '二级'},
      ],
      pd: {},// 数据
      measuresList: [],
      modalName: null,
      imgList: [],
    }
  },
  onLoad(event) {
    this.todayDate = formatDate(new Date(), 'yyyy-MM-dd hh:mm');
    this.pd.ELECTRICITY_ID = event.ELECTRICITY_ID;
    if (this.pd.ELECTRICITY_ID) {
      this.msg = "edit";
      this.getData();
    } else {
      // 初始化作业负责人
      this.pd.APPLY_DEPARTMENT_ID = loginUser.DEPARTMENT_ID;
      this.pd.APPLY_DEPARTMENT_NAME = loginUser.DEPARTMENT_NAME;
      this.pd.APPLY_USER_ID = loginUser.USER_ID;
      this.pd.APPLY_USER_NAME = loginUser.NAME;
      this.forbidEdit = false;
    }
    // 初始化现场作业负责人
    this.getDept();
    this.getLimitSpace();
    loginSession();

  },
  methods: {
    //跳转事件
    goToDetail(e) {
      uni.navigateTo({
        url: '/pages/application/electricity/electricity-gas/gas-list?ELECTRICITY_ID=' + e
      });
    },
    getData() {
      var _this = this;
      uni.showLoading({
        title: '请稍候'
      })
      uni.request({
        url: basePath + '/app/electricity/findById',
        method: 'POST',
        header: {
          'Content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          ELECTRICITY_ID: _this.pd.ELECTRICITY_ID,
          CORPINFO_ID: loginUser.CORPINFO_ID,
          USER_ID: loginUser.USER_ID,
        },
        success: (res) => {
          if ("success" == res.data.result) {
            uni.hideLoading();
            _this.pd = res.data.pd; //参数map

          } else if ("exception" == data.result) {
            uni.showToast({
              title: '错误',
              duration: 2000
            });
          }
        }
      });
    },
    ViewShowImage(url) {
      let files = [];
      files.push(url)
      uni.previewImage({
        urls: files,
        current: 0
      });
    },
    goSubmit(APPLY_STATUS) {
      var _this = this;
      if (_this.imgList.length <= 0) {
        uni.showToast({
          icon: 'none',
          title: '请签字',
          duration: 1500
        });
        return;
      }
      uni.showModal({
        title: '请确认' + (APPLY_STATUS == 1 ? "通过" : "作废") + '本作业票？',
        placeholderText: '请输入作废原因',
        cancelColor: "#000000",
        cancelText: '取消',
        editable: APPLY_STATUS != 1,
        confirmText: '确定',
        success: res => {
          if (res.confirm) {
            if (APPLY_STATUS != 1 && !res.content) {
              uni.showToast({
                icon: 'none',
                title: '请填写作废原因',
                duration: 1500
              });
              return;
            }
            uni.showLoading({
              title: '请稍候'
            })
            const formData = {}
            var files = [];
            var signtime = [];

            this.uploadImgFaults(files, signtime)
            formData.APPLY_STATUS = APPLY_STATUS
            formData.SIGNTIME = signtime.join(",")
            formData.ELECTRICITY_ID = this.pd.ELECTRICITY_ID
            formData.STEP_REASON = res.content ? res.content : ''
            formData.USER_ID = loginUser.USER_ID
            uni.uploadFile({
              url: basePath + 'app/electricity/nextStep',
              files: files,
              formData: formData,
              success: (res) => {
                uni.showToast({
                  icon: 'none',
                  title: '保存成功',
                  duration: 2000
                });
                _this.goback()
              },
              fail: (err) => {
                uni.hideLoading();
                uni.showModal({
                  content: err.errMsg,
                  showCancel: false
                });
              }
            })
          }
        }
      })
    },
    // 获取动火列表
    getLimitSpace() {
      var _this = this;
      uni.request({
        method: 'POST',
        dataType: 'json',
        header: {
          'Content-type': 'application/x-www-form-urlencoded'
        },
        url: basePath + '/app/limitspace/listAllSpace?tm=' + new Date().getTime(),
        data: {
          CORPINFO_ID: loginUser.CORPINFO_ID,
          USER_ID: loginUser.USER_ID,
        },
        success: function (res) {
          _this.limitSpaceList = res.data.varList;
        }
      });
    },
    getDept() {
      var _this = this;
      uni.request({
        url: basePath + '/app/sys/listTree',//部门下拉接口
        method: 'POST',
        dataType: 'json',
        header: {
          'Content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          CORPINFO_ID: loginUser.CORPINFO_ID,
          USER_ID: loginUser.USER_ID,
        },
        success: (res) => {
          if ("success" == res.data.result) {
            _this.treeNode = eval(res.data.zTreeNodes);
          } else {
            uni.showToast({
              title: res.data.message,
              duration: 2000
            });
          }
        }
      });
    },
    //获取人员列表
    getUserList(dept, list, i) {
      //发送 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: dept,
          tm: new Date().getTime(),
          CORPINFO_ID: loginUser.CORPINFO_ID,
          USER_ID: loginUser.USER_ID,
        },
        success: function (res) {
          if ("success" == res.data.result) {
            if (i > -1) {
              _this[list][i] = [];
              _this[list][i] = res.data.userList;
              _this.$forceUpdate();//强制刷新
            } else {
              _this[list] = res.data.userList;
            }
          } else {
            uni.showToast({
              title: res.data.message,
              duration: 2000
            });
          }
        }
      })
    },

    /*
       *手写板
       */
    showModal() {
      this.modalName = 'Modal'
    },
    hideModal(e) {
      this.modalName = null
    },
    //完成
    subCanvas(e) {
      let t = {
        id: "",
        filePath: e.tempFile,
        SIGNER_TIME: formatDate(new Date(), 'yyyy-MM-dd hh:mm')
      }
      this.imgList.push(t);
      this.hideModal()
    },
    ViewImage(e) {
      let files = [];
      files.push(e.currentTarget.dataset.url)
      uni.previewImage({
        urls: files,
        current: e.currentTarget.dataset.url
      });
    },
    DelImg(index) {
      this.imgList.splice(index, 1)
    },
    uploadImgFaults(files, signtime) {
      this.imgList.map((item, index) => {
        var img = {}
        img.name = 'file' + index
        img.uri = item.filePath
        files.push(img)
        signtime.push(item.SIGNER_TIME)
      })
    },
    /*
    *分析人
     */
    // 确定回调事件
    analyzetreeConfirm(e) {
      this.isUps = false;
      this.pd.ANALYZE_DEPARTMENT_ID = e[0].id;
      this.pd.ANALYZE_DEPARTMENT_NAME = e[0].name;
      this.$forceUpdate();//强制刷新
      this.getUserList(e[0].id, 'analyzeUserList');
    },
    // 取消回调事件
    analyzetreeCancel(e) {
      this.isUps = false;
    },
    // 显示树形选择器
    showAnalyzeTree() {
      this.isUps = true
      this.$refs.tkiTree_analyze._show();
    },
    PickerAnalyze(e) {
      this.analyzeindex = e.detail.value;
      this.pd.ANALYZE_USER_ID = this.analyzeUserList[this.analyzeindex].USER_ID;
      this.pd.ANALYZE_USER_NAME = this.analyzeUserList[this.analyzeindex].NAME;
      this.$forceUpdate();//强制刷新
    },

    /*
    *监护人
     */
    // 确定回调事件
    guardiantreeConfirm(e) {
      this.isUps = false;
      this.pd.GUARDIAN_DEPARTMENT_ID = e[0].id;
      this.pd.GUARDIAN_DEPARTMENT_NAME = e[0].name;
      this.$forceUpdate();//强制刷新
      this.getUserList(e[0].id, 'guardianUserList');
    },
    // 取消回调事件
    guardiantreeCancel(e) {
      this.isUps = false;
    },
    // 显示树形选择器
    showGuardianTree() {
      this.isUps = true
      this.$refs.tkiTree_guardian._show();
    },
    PickerGuardian(e) {
      this.guardianindex = e.detail.value;
      this.pd.GUARDIAN_USER_ID = this.guardianUserList[this.guardianindex].USER_ID;
      this.pd.GUARDIAN_USER_NAME = this.guardianUserList[this.guardianindex].NAME;
      this.$forceUpdate();//强制刷新
    },

    goback() {
      var pages = getCurrentPages();	// 获取当前页面栈
      var prePage = pages[pages.length - 2];	// 上二级页面
      prePage.$vm.initflag = true;    // A 页面 init方法 为true
      uni.navigateBack({delta: 1});
      uni.hideLoading();
    },
    radioType(e) {
      this.HASINSTRUCTOR = e.detail.value
    },
    goToEdit() {
      this.forbidEdit = false;
    }
  }
}
</script>

<style scoped>
.wui-sign-box1 {
  margin-top: 20upx;
  display: block;
}

.sign-img {
  position: relative;
  border-bottom: 1px dashed #eee;
  padding-top: 20upx;
}

.cu-tag {
  position: absolute;
  right: 20upx;
  top: 20upx;
}
</style>
