<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.BLINDBOARD_ID" :blindboardId="pd.BLINDBOARD_ID"></detail>
        <view class="wui-form-list cu-form-group bb-default">
          <view class="title" style="font-weight: bold">设备管道名称：</view>
          <input name="input" ref="NAME" v-model="pd.NAME"
                 placeholder="请输入设备管道名称"></input>
        </view>

        <view class="wui-form-list">
          <view class="wui-sub-title">
            <text>管道参数</text>
          </view>
          <view class="cu-form-group">
            <view class="title">介质：</view>
            <input name="input" ref="MEDIUM" v-model="pd.MEDIUM"
                   placeholder="请输入介质"></input>
          </view>

          <view class="cu-form-group">
            <view class="title">温度：</view>
            <input name="input" ref="TEMPERATURE" v-model="pd.TEMPERATURE"
                   placeholder="请输入温度"></input>
          </view>

          <view class="cu-form-group">
            <view class="title">压力：</view>
            <input name="input" ref="PRESSURE" v-model="pd.PRESSURE"
                   placeholder="请输入压力"></input>
          </view>
        </view>

        <view class="wui-form-list" v-for="(item,index) of boardList">
          <view class="wui-sub-title" style="display: flex;justify-content: space-between">
            <text style="height:32upx; border: none; position: relative;">
              <view
                  style="width: 8upx; height: 32upx; background: #1d82fe; position: absolute; top: 6upx; left: 0;"></view>
              盲板抽堵参数
            </text>
            <button v-if="index == 0 " class="cu-btn round bg-blue" style="height:40upx;"
                    @click="addBoard">添加
            </button>
            <button v-if="index > 0 " class="cu-btn round bg-red" style="height:40upx;"
                    @click="removeBoard(index)">删除
            </button>
          </view>
          <view class="cu-form-group">
            <view class="title">材质：</view>
            <input name="input" ref="BOARD_MATERIAL" v-model="boardList[index].BOARD_MATERIAL"
                   placeholder="请输入材质"></input>
          </view>

          <view class="cu-form-group">
            <view class="title">规格：</view>
            <input name="input" ref="BOARD_SPECIFICATION"
                   v-model="boardList[index].BOARD_SPECIFICATION" placeholder="请输入规格"></input>
          </view>

          <view class="cu-form-group">
            <view class="title">编号：</view>
            <input name="input" ref="BOARD_NO" v-model="boardList[index].BOARD_NO"
                   placeholder="请输入编号"></input>
          </view>
        </view>
        <view class="wui-form-list">
<!--          <view class="cu-form-textarea">-->
<!--            <view class="cu-form-title">盲板抽堵位置及安全措施：</view>-->

<!--          </view>-->
          <view class="cu-bar">
            <view class="action"  style="font-weight: bold;">
              盲板抽堵位置图：
            </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 conimgList" :key="index" @tap="viewImage(index,'conimgList')">
                <image :src="baseImgPath + item.filePath" mode="aspectFill"></image>
                <view class="cu-tag bg-red" @tap.stop="delImgs" data-type="2" :data-index="index">
                  <text class='cuIcon-close'></text>
                </view>
              </view>
              <view class="solids" @tap="chooseImages()">
                <text class='cuIcon-cameraadd'></text>
              </view>
            </view>
          </view>
        </view>


        <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/blindboard/blindboard-detail/index'

export default {
  components: {
    tkiTree, ruiDatePicker, writingBoard, detail
  },
  data() {
    return {
      boardList: [{"BOARD_MATERIAL": '', "BOARD_SPECIFICATION": '', "BOARD_NO": ''}],
      baseImgPath: baseImgPath,
      isUps: false,
      forbidEdit: true,// 禁止修改
      msg: 'add',
      files: [],
      noClick: true,
      treeNode: [],//部门下拉数据
      pd: {},
      measuresList: [],
      modalName: null,
      imgList: [],
      conimgList: [],
      rules:
          [
            {name: 'NAME', message: '请输入设备管线名'},
            {name: 'MEDIUM', message: '请输入介质'},
            {name: 'TEMPERATURE', message: '请输入温度'},
            {name: 'PRESSURE', message: '请输入压力'},
            // {name:'BOARD_MATERIAL',message:'请输入材质'},
            // {name:'BOARD_SPECIFICATION',message:'请输入规格'},
            // {name:'BOARD_NO',message:'请输入编号'},
          ],
    }
  },
  onLoad(event) {
    this.todayDate = formatDate(new Date(), 'yyyy-MM-dd hh:mm');
    this.pd.BLINDBOARD_ID = event.BLINDBOARD_ID;
    if (this.pd.BLINDBOARD_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: {
    delImgs(e) {
      var _this = this;
      uni.showModal({
        title: '新泰安全',
        content: '确定要删除这张图片吗？',
        cancelColor: "#000000",
        cancelText: '取消',
        confirmText: '确定',
        success: res => {
          if (res.confirm) {
            uni.request({
              url: basePath + '/app/eightwork/deleteFile',
              method: 'POST',
              dataType: 'json',
              header: {
                'Content-type': 'application/x-www-form-urlencoded'
              },
              data: {
                FILE_PATH: _this.conimgList[e.currentTarget.dataset.index].filePath
              },
              success: (res) => {
                uni.showToast({
                  icon: 'none',
                  title: '删除成功',
                  duration: 1500
                });
                this.conimgList.splice(e.currentTarget.dataset.index, 1)
              },
              fail: (err) => {
                uni.showModal({
                  content: "删除失败",
                  showCancel: false
                });
              }
            })
          }
        }
      })
    },
    chooseImages() {
      uni.chooseImage({
        count: 1, //默认9
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['camera', 'album'], //从相册选择
        success: (res) => {
          uni.uploadFile({
            url: basePath + '/app/eightwork/saveFile',
            filePath: res.tempFilePaths[0],
            name: 'file',
            formData: {
              CORPINFO_ID: loginUser.CORPINFO_ID,
            },
            success: ({data}) => {
              let img = {};
              img.filePath = JSON.parse(data).FILE_PATH;
              this.conimgList.push(img)
              console.log(this.conimgList)
            },
            fail: (err) => {
              uni.showModal({
                content: "图片上传失败",
                showCancel: false
              });
            }
          })
        }
      });
    },
    addBoard: function () {
      var _this = this;
      let o = {"BOARD_MATERIAL": '', "BOARD_SPECIFICATION": '', "BOARD_NO": ''};
      _this.boardList.push(o);
    },
    removeBoard: function (index) {
      this.boardList.splice(index, 1);
    },
    //跳转事件
    goToDetail(e) {
      uni.navigateTo({
        url: '/pages/application/blindboard/blindboard-gas/gas-list?BLINDBOARD_ID=' + e
      });
    },
    getData() {
      var _this = this;
      uni.showLoading({
        title: '请稍候'
      })
      uni.request({
        url: basePath + '/app/blindboard/findById',
        method: 'POST',
        header: {
          'Content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          BLINDBOARD_ID: _this.pd.BLINDBOARD_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
            });
          }
        }
      });
    },
    goSubmit(APPLY_STATUS) {
      var _this = this;
      let required = true
      if (APPLY_STATUS === 1) {
        this.rules.map(({name, message}) => {
          if (!this.pd[name]) {
            uni.showToast({
              icon: 'none',
              title: message,
              duration: 1500
            });
            required = false
          }
        })
        for (let i = 0; i < this.boardList.length; i++) {
          if(!this.boardList[i].BOARD_MATERIAL || !this.boardList[i].BOARD_SPECIFICATION || !this.boardList[i].BOARD_NO){
            uni.showToast({
              icon: 'none',
              title: '请输入盲板材质，规格或编号',
              duration: 1500
            });
          }
        }
        if (!required) {
          return
        }
      }
      if (_this.imgList.length <= 0) {
        uni.showToast({
          icon: 'none',
          title: '请签字',
          duration: 1500
        });
        return;
      }
      if (APPLY_STATUS === 1) {
        if (_this.conimgList.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: '请稍候'
            })
            var fileList = [];
            var signtime = [];
            const formData = {}
            Object.keys(this.pd).map(key => {
              formData[key] = this.pd[key]
            })
            this.uploadImgFaults(fileList, signtime)
            formData.SIGNTIME = signtime.join(",")
            formData.BLINDBOARD_ID = this.pd.BLINDBOARD_ID
            formData.USER_ID = loginUser.USER_ID
            formData.APPLY_STATUS = APPLY_STATUS
            formData.STEP_REASON = res.content ? res.content : ''
            formData.boardList = JSON.stringify(this.boardList)
            formData.CONIMG_PATH = this.conimgList.map(item => {
              return item.filePath
            }).join(",")
            uni.uploadFile({
              url: basePath + 'app/blindboard/nextStep',
              files: fileList,
              formData: formData,
              success: (res) => {
                uni.showToast({
                  icon: 'none',
                  title: '保存成功',
                  duration: 2000
                });
                _this.goback()
              },
              fail: (err) => {
                uni.hideLoading();
                uni.showModal({
                  content: err.errMsg,
                  showCancel: false
                });
              }
            })
          }
        }
      })
    },
    uploadImgFaults(fileList, signtime) {
      this.imgList.map(item => {
        var img = {}
        img.name = 'file' + (fileList.length)
        img.uri = item.filePath
        fileList.push(img)
        signtime.push(item.SIGNER_TIME)
      })
    },
    DelImg(index) {
      this.imgList.splice(index, 1)
    },
    // 获取动火列表
    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(ISSELF) {
      this.ISSELF = ISSELF
      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
      });
    },

    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>
