<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>
          <input v-model="form.CHECK_NO" disabled placeholder="请输入编号"></input>
        </view>
        <view class="cu-form-group">
          <view class="title">申请部门：</view>
          {{ form.APPLY_DEPARTMENT_NAME }}
        </view>
        <view class="cu-form-group">
          <view class="title">申请人：</view>
          {{ form.APPLY_USER_NAME }}
        </view>
        <view class="cu-form-group">
          <view class="title">设备管线名称：</view>
          <input :disabled="forbidEdit" v-model="form.NAME" placeholder="请输入设备管线名称"></input>
        </view>
        <view class="cu-form-group">
          <view class="title">介质：</view>
          <input :disabled="forbidEdit" v-model="form.MEDIUM" placeholder="请输入介质"></input>
        </view>
        <view class="cu-form-group">
          <view class="title">温度：</view>
          <input :disabled="forbidEdit" v-model="form.TEMPERATURE" placeholder="请输入温度，单位摄氏度" type="number"></input>
        </view>
        <view class="cu-form-group">
          <view class="title">盲板材质：</view>
          <input :disabled="forbidEdit" v-model="form.BOARD_MATERIAL" placeholder="请输入盲板材质"></input>
        </view>
        <view class="cu-form-group">
          <view class="title">盲板规格：</view>
          <input :disabled="forbidEdit" v-model="form.BOARD_SPECIFICATION" placeholder="请输入盲板规格"></input>
        </view>
        <view class="cu-form-group">
          <view class="title">盲板编号：</view>
          <input :disabled="forbidEdit" v-model="form.BOARD_NO" placeholder="请输入盲板编号"></input>
        </view>
        <view class="cu-form-group">
          <view class="title">实施时间装：</view>
          <ruiDatePicker v-if="!forbidEdit" :start="todayDate" fields="minute" :value="form.BOARD_INSTALL_TIME || '请选择'"
                         @change="changeJobStartTime"></ruiDatePicker>
          <text v-else>{{ form.BOARD_INSTALL_TIME }}</text>
        </view>
        <view class="cu-form-group">
          <view class="title">实施时间拆：</view>
          <ruiDatePicker v-if="!forbidEdit" :start="todayDate" fields="minute" :value="form.BOARD_DISASSEMBLE_TIME || '请选择'"
                         @change="changeJobEndTime"></ruiDatePicker>
          <text v-else>{{ form.BOARD_DISASSEMBLE_TIME }}</text>
        </view>
        <view class="cu-form-group">
          <view class="title">作业人装：</view>
          <input :disabled="forbidEdit" v-model="form.BOARD_INSTALL_USER" placeholder="请输入作业人装"></input>
        </view>
        <view class="cu-form-group">
          <view class="title">作业人拆：</view>
          <input :disabled="forbidEdit" v-model="form.BOARD_DISASSEMBLE_USER" placeholder="请输入作业人拆"></input>
        </view>
        <view class="cu-form-group">
          <view class="title">监护人装：</view>
          <input :disabled="forbidEdit" v-model="form.BOARD_INSTALL_CUSTODY_USER" placeholder="请输入监护人装"></input>
        </view>
        <view class="cu-form-group">
          <view class="title">监护人拆：</view>
          <input :disabled="forbidEdit" v-model="form.BOARD_DISASSEMBLE_CUSTODY_USER" placeholder="请输入监护人拆"></input>
        </view>
        <view class="cu-form-group">
          <view class="title">盲板位置图：</view>
          {{form.imgList.length}}/4
        </view>
        <view class="cu-form-group" style="padding-top:20upx">
          <view class="grid col-4 grid-square flex-sub">
            <view class="bg-img" v-for="(item,index) in form.imgList" :key="index" @tap="ViewImage" :data-url="form.imgList[index]">
              <image :src="form.imgList[index]" mode="aspectFill"></image>
              <view class="cu-tag bg-red" @tap.stop="DelImg1" :data-index="index" v-if="!forbidEdit">
                <text class='cuIcon-close'></text>
              </view>
            </view>
            <view class="solids" @tap="ChooseImage" v-if="form.imgList.length<4 && !forbidEdit">
              <text class='cuIcon-cameraadd'></text>
            </view>
          </view>
        </view>
        <view class="cu-form-group">
          <view class="title">编制人签字：</view>
          <button class="cu-btn bg-green shadow" @tap="modalShow = true" data-target="Modal" v-if="!forbidEdit">手写签字</button>
        </view>
        <view class="cu-bar bg-white" v-show="imgList && imgList.length > 0">
          <view class="action">
            签字照片
          </view>
        </view>
        <view class="cu-form-group" v-show="imgList && imgList.length > 0">
          <view class="grid col-4 grid-square flex-sub">
            <view style="width: 60%;" class="bg-img" v-for="(item,index) in imgList" :key="index" @tap="ViewImage1" data-type="0" :data-url="imgList[index].filePath">
              <image :src="imgList[index].filePath" mode="aspectFill"></image>
              <view class="cu-tag bg-red" @tap.stop="DelImg" data-type="0" :data-index="index" v-if="!forbidEdit">
                <text class='cuIcon-close'></text>
              </view>
            </view>
          </view>
        </view>
        <view class="cu-modal" :class="{'show':modalShow}">
          <sign @confirm="subCanvas" @cancel="modalShow = false"></sign>
        </view>

        <view class="cu-form-group">
          <view class="title">作业地点：</view>
          <input name="input" ref="WORK_PLACE" :disabled="forbidEdit" v-model="form.WORK_PLACE" placeholder="请输入作业地点"></input>
        </view>
        <view class="cu-form-group">
          <view class="title">地点坐标：</view>
          <button class="cu-btn shadow bg-blue" @click="chooseLocation" v-if="!forbidEdit">地图选择</button>
        </view>
        <view class="cu-form-group" v-if="form.LONGITUDE">
          <view class="title">经度：</view>
          <view>{{form.LONGITUDE}}</view>
        </view>
        <view class="cu-form-group" v-if="form.LATITUDE">
          <view class="title">纬度：</view>
          <view>{{form.LATITUDE}}</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('tkiTree1')">
                {{ form.WORK_UNIT_MANAGER_DEPARTMENT_NAME || '请选择' }}
              </view>
            </view>
            <tki-tree ref="tkiTree1" :selectParent=true :range="treeNode" rangeKey="name" @confirm="zgtreeConfirm($event,'workUnitManagerList')"
                      @cancel="zgtreeCancel"></tki-tree>
          </block>
          <block v-else>{{ form.WORK_UNIT_MANAGER_DEPARTMENT_NAME }}</block>
        </view>
        <view class="cu-form-group" v-if="form.WORK_UNIT_MANAGER_DEPARTMENT_NAME">
          <view class="title">作业单位负责人：</view>
          <picker @change="workUnitManagerChange" :disabled="forbidEdit" :value="form.OPERATION_UNIT_PERSONCHARGE_INDEX"
                  :range="workUnitManagerList" range-key="NAME">
            <view class="picker">
              {{ form.OPERATION_UNIT_PERSONCHARGE_NAME || '请选择' }}
            </view>
          </picker>
        </view>
        <view class="cu-form-group">
          <view class="title" style="height: auto;">
            <view>分公司（中心）审批人</view>
            <view>部门：</view>
          </view>
          <block v-if="!forbidEdit">
            <view class="picker-tree-box">
              <view class="picker-tree" @tap="showZgTree('tkiTree2')">
                {{ form.BRANCH_APPROVER_DEPARTMENT_NAME || '请选择' }}
              </view>
            </view>
            <tki-tree ref="tkiTree2" :selectParent=true :range="treeNode" rangeKey="name" @confirm="zgtreeConfirm($event,'branchApproverList')"
                      @cancel="zgtreeCancel"></tki-tree>
          </block>
          <block v-else>{{ form.BRANCH_APPROVER_DEPARTMENT_NAME }}</block>
        </view>
        <view class="cu-form-group" v-if="form.BRANCH_APPROVER_DEPARTMENT_NAME">
          <view class="title">分公司（中心）审批人：</view>
          <picker @change="branchApproverChange" :disabled="forbidEdit" :value="form.CORPINFO_APPROVER_INDEX"
                  :range="branchApproverList" range-key="NAME">
            <view class="picker">
              {{ form.CORPINFO_APPROVER_NAME || '请选择' }}
            </view>
          </picker>
        </view>
      </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="$noMultipleClicks(goSubmit)">提交
      </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>
</template>

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

export default {
  components: {
    tkiTree,
    ruiDatePicker,
    sign
  },
  data() {
    return {
      noClick: true,
      BLINDBOARD_ID: '',
      form: {
        APPLY_DEPARTMENT_ID: '',
        APPLY_DEPARTMENT_NAME: '',
        APPLY_USER_ID: '',
        APPLY_USER_NAME: '',
        CHECK_NO: '',
        NAME: '',
        MEDIUM: '',
        TEMPERATURE: '',
        BOARD_MATERIAL: '',
        BOARD_SPECIFICATION: '',
        BOARD_NO: '',
        BOARD_INSTALL_TIME: '',
        BOARD_DISASSEMBLE_TIME: '',
        BOARD_INSTALL_USER: '',
        BOARD_DISASSEMBLE_USER: '',
        BOARD_INSTALL_CUSTODY_USER: '',
        BOARD_DISASSEMBLE_CUSTODY_USER: '',
        imgList: [],
        WORK_PLACE: '',
        LONGITUDE: '',
        LATITUDE: '',
        WORK_UNIT_MANAGER_DEPARTMENT_NAME: '',
        WORK_UNIT_MANAGER_DEPARTMENT_ID: '',
        OPERATION_UNIT_PERSONCHARGE_NAME: '',
        OPERATION_UNIT_PERSONCHARGE_INDEX: '',
        OPERATION_UNIT_PERSONCHARGE: '',
        BRANCH_APPROVER_DEPARTMENT_NAME: '',
        BRANCH_APPROVER_DEPARTMENT_ID: '',
        CORPINFO_APPROVER_NAME: '',
        CORPINFO_APPROVER_INDEX: '',
        CORPINFO_APPROVER: '',
      },
      rules: [
        {name: 'CHECK_NO', message: '请输入编号'},
        {name: 'NAME', message: '请输入设备管线名称'},
        {name: 'MEDIUM', message: '请输入介质'},
        {name: 'TEMPERATURE', message: '请输入温度'},
        {name: 'BOARD_MATERIAL', message: '请输入盲板材质'},
        {name: 'BOARD_SPECIFICATION', message: '请输入盲板材质'},
        {name: 'BOARD_NO', message: '请输入盲板编号'},
        {name: 'BOARD_INSTALL_TIME', message: '请选择实施时间装'},
        {name: 'BOARD_DISASSEMBLE_TIME', message: '请选择实施时间拆'},
        {name: 'BOARD_INSTALL_USER', message: '请输入作业人装'},
        {name: 'BOARD_DISASSEMBLE_USER', message: '请输入作业人拆'},
        {name: 'BOARD_INSTALL_CUSTODY_USER', message: '请输入监护人装'},
        {name: 'BOARD_DISASSEMBLE_CUSTODY_USER', message: '请输入监护人拆'},
        {name: 'WORK_PLACE',message:'请输入作业地点'},
        // {name: 'LONGITUDE', message: '请选择作业坐标'},
        // {name: 'LATITUDE', message: '请选择作业坐标'},
        {name: 'WORK_UNIT_MANAGER_DEPARTMENT_NAME', message: '请选择作业单位负责人部门'},
        {name: 'OPERATION_UNIT_PERSONCHARGE_NAME', message: '请选择作业单位负责人'},
        {name: 'BRANCH_APPROVER_DEPARTMENT_NAME', message: '请选择分公司（中心）审批人部门'},
        {name: 'CORPINFO_APPROVER_NAME', message: '请选择分公司（中心）审批人'},
      ],
      treeNode: [],
      forbidEdit: false,
      todayDate: formatDate(new Date(), 'yyyy-MM-dd hh:mm'),
      modalShow: false,
      imgList: [],
      workUnitManagerList: [],
      branchApproverList: [],
    }
  },
  onLoad(event) {
    if (event.id) {
      this.BLINDBOARD_ID = event.id
      this.forbidEdit = true
      this.getData();
    } else {
      this.createWorkNumber()
      // 初始化作业负责人
      this.form.APPLY_DEPARTMENT_ID = loginUser.DEPARTMENT_ID;
      this.form.APPLY_DEPARTMENT_NAME = loginUser.DEPARTMENT_NAME;
      this.form.APPLY_USER_ID = loginUser.USER_ID;
      this.form.APPLY_USER_NAME = loginUser.NAME;
      this.form.LONGITUDE = ''
      this.form.LATITUDE = ''
      // this.form.LONGITUDE = '119.65772151947023'
      // this.form.LATITUDE = '39.93767832107088'
    }
    loginSession();
    this.getDept()
  },
  methods: {
    createWorkNumber() {
      var _this = this;
      uni.request({
        url: basePath + '/app/serialnumber/add',
        method: 'POST',
        header: {
          'Content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          TYPE: 'MB',
          CORPINFO_ID: corpinfoId
        },
        success: (res) => {
          if ("success" === res.data.result) {
            this.$set(_this.form, 'CHECK_NO', res.data.pd.NUMBER) //参数map
          }
        }
      });
    },
    getData() {
      var _this = this;
      uni.showLoading({
        title: '请稍候'
      })
      uni.request({
        url: basePath + '/app/blindboard/personChargeGoEdit',
        method: 'POST',
        header: {
          'Content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          BLINDBOARD_ID: _this.BLINDBOARD_ID,
        },
        success: (res) => {
          if ("success" === res.data.result) {
            this.form = res.data.varList;
            if(res.data.varList.BOARD_SIGNER_PATH){
              this.imgList = [{filePath: baseImgPath + res.data.varList.BOARD_SIGNER_PATH}];
            }
            this.$set(this.form, 'imgList', []);
            for (let i = 0; i < res.data.imgList.length; i++) {
              this.form.imgList.push(baseImgPath + res.data.imgList[i].FILEPATH);
            }
            if (Number(res.data.varList.APPLY_STATUS) < 1) this.forbidEdit = false;
            else this.forbidEdit = true;
            uni.hideLoading();
          } else if ("exception" === res.data.result) {
            uni.showToast({
              title: '错误',
              duration: 2000
            });
          }
        }
      });
    },
    goSubmit() {
      var _this = this;
      let required = true
      this.rules.map(({name, message}) => {
        if (!this.form[name]) {
          uni.showToast({
            icon: 'none',
            title: message,
            duration: 1500
          });
          required = false
        }
      })
      if(this.form.imgList.length === 0){
        uni.showToast({
          icon: 'none',
          title: '请上传盲板位置图',
          duration: 1500
        })
        required = false
      }
      if(this.imgList.length === 0){
        uni.showToast({
          icon: 'none',
          title: '请签字',
          duration: 1500
        })
        required = false
      }
      if (!required) {
        return
      }
      uni.showLoading({
        title: '请稍候'
      })
      let url = ''
      let formData = {}
      if(!this.BLINDBOARD_ID){
        url = '/app/blindboard/add'
        formData = {
          ...this.form,
          BOARD_SIGNER_TIME: formatDate(new Date(), 'yyyy-MM-dd hh:mm'),
          CORPINFO_ID:corpinfoId
        }
      }else {
        url = '/app/blindboard/edit'
        formData = {
          ...this.form,
          BOARD_SIGNER_TIME: formatDate(new Date(), 'yyyy-MM-dd hh:mm'),
          CORPINFO_ID:corpinfoId,
          BLINDBOARD_ID: this.BLINDBOARD_ID
        }
      }
      uni.uploadFile({
        url: basePath + url,
        filePath: this.imgList[0].filePath,
        name: 'BOARD_SIGNER_PATH',
        formData,
        success: (res) => {
          console.log(JSON.parse(res.data))
          console.log(JSON.parse(res.data).ID)
          for (let i = 0; i < this.form.imgList.length; i++) {
            uni.uploadFile({
              url: basePath + "/app/blindboard/uploadImg",
              filePath: this.form.imgList[i],
              name: 'FFILE',
              formData: {
                BLINDBOARD_ID: JSON.parse(res.data).ID || JSON.parse(res.data).BLINDBOARD_ID
              },
              success: () => {
                if(i === this.form.imgList.length - 1){
                  uni.hideLoading();
                  uni.showToast({
                    title: '提交成功',
                    duration: 1500
                  });
                  _this.goback()
                }
              },
              fail: (err) => {
                uni.hideLoading();
                uni.showModal({
                  content: err.errMsg,
                  showCancel: false
                });
              }
            })
          }
        },
      });
    },
    changeJobStartTime(e) {
      this.form.BOARD_INSTALL_TIME = e
    },
    changeJobEndTime(e) {
      this.form.BOARD_DISASSEMBLE_TIME = e
    },
    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: 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();
    },
    zgtreeConfirm(e, list) {
      if (list === "workUnitManagerList") {
        this.form.WORK_UNIT_MANAGER_DEPARTMENT_ID = e[0].id;
        this.form.WORK_UNIT_MANAGER_DEPARTMENT_NAME = e[0].name;
        this.form.OPERATION_UNIT_PERSONCHARGE_INDEX = '';
        this.form.OPERATION_UNIT_PERSONCHARGE = '';
        this.form.OPERATION_UNIT_PERSONCHARGE_NAME = '';
      }
      if (list === "branchApproverList") {
        this.form.BRANCH_APPROVER_DEPARTMENT_ID = e[0].id;
        this.form.BRANCH_APPROVER_DEPARTMENT_NAME = e[0].name;
        this.form.CORPINFO_APPROVER_INDEX = '';
        this.form.CORPINFO_APPROVER = '';
        this.form.CORPINFO_APPROVER_NAME = '';
      }
      this.getUserList(list, e[0].id);
    },
    workUnitManagerChange(e) {
      this.form.OPERATION_UNIT_PERSONCHARGE_INDEX = e.detail.value;
      this.form.OPERATION_UNIT_PERSONCHARGE = this.workUnitManagerList[e.detail.value].USER_ID;
      this.form.OPERATION_UNIT_PERSONCHARGE_NAME = this.workUnitManagerList[e.detail.value].NAME;
    },
    branchApproverChange(e) {
      this.form.CORPINFO_APPROVER_INDEX = e.detail.value;
      this.form.CORPINFO_APPROVER = this.branchApproverList[e.detail.value].USER_ID;
      this.form.CORPINFO_APPROVER_NAME = this.branchApproverList[e.detail.value].NAME;
    },
    zgtreeCancel(e) {
      this.isUps = false;
    },
    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
            });
          }
        }
      })
    },
    chooseLocation() {
      var _this = this
      uni.navigateTo({
        url: '/pages/map/mapPro',
        events: {
          // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
          acceptDataFromOpenedPage: function (e) {
            _this.form.LONGITUDE = e.data.longitue;
            _this.form.LATITUDE = e.data.latitude;
          }
        },
      })
    },
    ChooseImage() {
      var _this = this;
      uni.chooseImage({
        count: 4, //默认9
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['camera', 'album'], //从相册选择
        success: (res) => {
          if (this.form.imgList.length != 0) {
            this.form.imgList = this.form.imgList.concat(res.tempFilePaths)
          } else {
            this.form.imgList = res.tempFilePaths
          }
        }
      });
    },
    ViewImage(e) {
      uni.previewImage({
        urls: this.form.imgList,
        current: e.currentTarget.dataset.url
      });
    },
    DelImg(e) {
      uni.showModal({
        title: '双控平台',
        content: '确定要删除这张图片吗？',
        cancelColor: "#000000",
        cancelText: '取消',
        confirmText: '确定',
        success: res => {
          if (res.confirm) {
            this.imgList.splice(e.currentTarget.dataset.index, 1)
          }
        }
      })
    },
    subCanvas (e) {
      this.imgList.splice(0, this.imgList.length);
      this.imgList.push(e);
      this.modalShow = false;
    },
    ViewImage1 (e) {
      let files = [];
      for (var i = 0; i < this.imgList.length; i++) {
        files.push(this.imgList[i].filePath)
      }
      uni.previewImage({
        urls: files,
        current: e.currentTarget.dataset.url
      });
    },
    DelImg1(e) {
      uni.showModal({
        title: '双控平台',
        content: '确定要删除这张图片吗？',
        cancelColor: "#000000",
        cancelText: '取消',
        confirmText: '确定',
        success: res => {
          if (res.confirm) {
            this.form.imgList.splice(e.currentTarget.dataset.index, 1)
          }
        }
      })
    },
    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;
}
</style>
