<template>
  <view>
    <cu-custom bgColor="bg-gradual-blueness" :isBack="!selectMeasuresShow">
      <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" :showMeasures="false"></detail>

        <view class="wui-form-list" style="padding-top: 20upx;">
          <view class="wui-title"
                style="margin-left: 20upx;display: flex;justify-content: space-between;align-items: center">
            <text class="text-semi">安全防护措施</text>
            <button class="cu-btn round bg-blue" @click="addMeasuresListCopy" style="margin-right: 20upx;">添加</button>
          </view>
          <view>
            <view class="add_pard_item" v-for="(item,index) in measuresListCopy" :key="item.id">
              <view class="add_pard_del" @click="removeMeasuresListCopy(index)" v-if="index !== 0">
                <text class="cuIcon-roundclosefill text-red f40"></text>
              </view>
<!--              <view class="cu-form-group">-->
<!--                <view class="title">确认单位：</view>-->
<!--                <view class="picker-tree-box">-->
<!--                  <view class="picker-tree" @tap="showDeptTree(index)">-->
<!--                    {{ item.DEPARTMENT_NAME ? item.DEPARTMENT_NAME : '请选择' }}-->
<!--                  </view>-->
<!--                </view>-->
<!--                <tki-tree-->
<!--                    :ref="'tkiTree'+index"-->
<!--                    :selectParent=true-->
<!--                    :range="treeNode"-->
<!--                    rangeKey="name"-->
<!--                    @confirm="deptTreeConfirm($event,index)"-->
<!--                    @cancel="deptTreeCancel($event,index)">-->
<!--                </tki-tree>-->
<!--              </view>-->
<!--              <view class="cu-form-group">-->
<!--              <view class="title">确认人</view>-->
<!--              <view style="position: relative">-->
<!--                <view class="search-input">-->
<!--                  <input-->
<!--                      type="text"-->
<!--                      style="text-align: right"-->
<!--                      v-model="item.searchConfirmUser"-->
<!--                      placeholder="请选择"-->
<!--                      @input="filterConfirmUser(index)"-->
<!--                      @click="toggleConfirmDropdown(index)"-->
<!--                  >-->
<!--                  <view class="search-icon" @click="toggleConfirmDropdown(index)">-->
<!--                    <text class="cuIcon-right"></text>-->
<!--                  </view>-->
<!--                </view>-->
<!--                <view v-show="item.showAnalyzeDropdown" class="showbg" style="position: absolute; left: 0; top: 36px;">-->
<!--                  <view-->
<!--                      v-for="(user, i) in item.filteredConfirmUsers"-->
<!--                      :key="i"-->
<!--                      @click="selectConfirmUser(user,index)"-->
<!--                  >-->
<!--                    {{ user.NAME }}-->
<!--                  </view>-->
<!--                </view>-->
<!--              </view>-->
<!--            </view>-->


              <view class="cu-form-group">
                <view class="title">确认人</view>
                <view class="picker" @click="openPersonPopup(index)" style="font-size: 28upx; flex: 1; display: flex; align-items: center; justify-content: flex-end; padding-right: 20upx;">
                  {{ item.searchPerson || '请选择确认人' }}
                </view>
              </view>
              <!-- 自定义弹窗 -->
              <view :class="['cu-modal', {'show': personPopupShow}]" v-if="personPopupShow">
                <view class="cu-dialog">
                  <view class="cu-bar bg-white justify-end">
                    <view class="content">请选择确认人</view>
                    <view class="action" @tap="closePersonPopup">
                      <text class="cuIcon-close text-red"></text>
                    </view>
                  </view>
                  <view class="padding">
                    <!-- 搜索框 -->
                    <view class="search-input">
                      <input
                          type="text"
                          v-model="popupSearch"
                          placeholder="请输入关键字"
                          @input="filterPopupList"
                      />
                      <view class="search-icon">
                        <text class="cuIcon-search"></text>
                      </view>
                    </view>
                    <!-- 人员列表 -->
                    <scroll-view class="scroll-list" scroll-y="true" style="height: 400px; margin-top: 20px;">
                      <view v-for="(user, index) in filteredPopupList" :key="index" class="list-item" @click="selectPerson(user)">
                        {{ user.DEPT_POST_NAME }}
                      </view>
                    </scroll-view>
                  </view>
                  <view class="cu-bar bg-white justify-end">
                    <view class="action">
                      <button class="cu-btn line-green text-green" @click="closePersonPopup">取消</button>
                    </view>
                  </view>
                </view>
              </view>


              <view class="measures cu-form-group">
                <view style="flex: 1">
                  <view style="margin-top: 10upx;display: flex;justify-content: space-between;align-items: center">
                    <view class="title">安全措施：</view>
                    <view>
                      <button class="cu-btn round bg-blue" @click="fnSelectMeasures(index)">选择安全措施</button>
                    </view>
                  </view>
                  <view class="content" v-for="(item1,index1) in item.selectMeasures" :key="index1">
                    {{ index1 + 1 }} . {{ item1.PROTECTIVE_MEASURES }}
                  </view>
                </view>
              </view>
            </view>
          </view>
          <view class="wui-sign">
            <view class="title"></view>
            <button class="cu-btn bg-green shadow" @tap="showModal" data-target="Modal">新增手写签字</button>
          </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>
    <select-measures :measures-list="measuresList" v-model="measuresListCopy"
                     :visible.sync="selectMeasuresShow"
                     :index="selectMeasuresIndex" row-key="BUS_BLINDBOARD_MEASURES_ID"/>
  </view>
</template>

<script>
import {
  basePath, 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 ruiDatePicker from '@/components/rattenking-dtpicker/rattenking-dtpicker.vue';
import detail from '@/pages/application/blindboard/blindboard-detail/index'
import selectMeasures from "@/components/select_measures/index.vue";

export default {
  components: {
    tkiTree, ruiDatePicker, writingBoard, detail, selectMeasures
  },
  data() {
    return {
      baseImgPath: baseImgPath,
      buttonloading: false,
      noClick: true,
      treeNode: [],//部门下拉数据
      pd: {},// 数据
      measuresList: [],
      measuresListCopy: [],
      selectMeasuresShow: false,
      selectMeasuresIndex: -1,
      modalName: null,
      imgList: [],
      searchPerson: '',           // 显示在表单中的值
      personPopupShow: false,     // 控制弹窗显示
      popupSearch: '',            // 弹窗内的搜索关键词
      filteredPopupList: [],      // 弹窗内过滤后的人员列表
      personList: [],             // 人员列表原始数据
      currentSelectIndex: -1,     // 当前选择的项索引
    }
  },
  onLoad(event) {
    this.pd.BLINDBOARD_ID = event.BLINDBOARD_ID;
    this.getData();
    // 初始化现场作业负责人
    this.getDept();
    this.getMeasures();
    this.addMeasuresListCopy();
    loginSession();
  },
  methods: {

    openPersonPopup(index) {
      this.currentSelectIndex = index;
      const item = this.measuresListCopy[index];
      this.popupSearch = item.searchPerson ? item.searchPerson.split('(')[0] : '';
      if (this.popupSearch.trim()) {
        this.filterPopupList();
      } else {
        this.getPersonList();
        this.filteredPopupList = [...this.personList];
      }
      this.personPopupShow = true;
    },

    closePersonPopup() {
      this.personPopupShow = false;
      const query = this.popupSearch.trim().toLowerCase();
      if (!query) {
        this.filteredPopupList = [...this.personList];
      } else {
        this.filteredPopupList = this.personList.filter(user => {
          const deptPostName = user.DEPT_POST_NAME ? user.DEPT_POST_NAME.toLowerCase() : '';
          const userId = user.USER_ID ? user.USER_ID.toLowerCase() : '';
          return deptPostName.includes(query) || userId.includes(query);
        });
      }
    },

    getPersonList() {
      uni.showLoading({
        title: '加载中...',
        mask: true
      });

      uni.request({
        method: 'POST',
        dataType: 'json',
        header: {
          'Content-type': 'application/x-www-form-urlencoded'
        },
        url: basePath + '/app/sys/listAllUserDePtAnfPost',
        data: {
          tm: new Date().getTime(),
          CORPINFO_ID: loginUser.CORPINFO_ID,
          USER_ID: loginUser.USER_ID,
        },
        success: (res) => {
          uni.hideLoading();
          if (res.data.result === 'success') {
            this.personList = res.data.userList || [];
            this.filteredPopupList = [...this.personList];
          } else {
            uni.showToast({
              title: res.data.message || '获取人员失败',
              duration: 2000,
              icon: 'none'
            });
          }
        },
        fail: () => {
          uni.hideLoading();
          uni.showToast({
            title: '网络请求失败',
            duration: 2000,
            icon: 'none'
          });
        }
      });
    },

    filterPopupList() {
      const query = this.popupSearch.trim().toLowerCase();
      if (!query) {
        this.filteredPopupList = [...this.personList];
      } else {
        this.filteredPopupList = this.personList.filter(user => {
          const deptPostName = user.DEPT_POST_NAME ? user.DEPT_POST_NAME.toLowerCase() : '';
          const userId = user.USER_ID ? user.USER_ID.toLowerCase() : '';
          return deptPostName.includes(query) || userId.includes(query);
        });
      }
    },

    selectPerson(user) {
      const index = this.currentSelectIndex;
      const item = this.measuresListCopy[index];

      for (let j = 0; j < this.measuresListCopy.length; j++) {
        if (this.measuresListCopy[j].USER_ID === user.USER_ID && index !== j) {
          uni.showToast({
            icon: 'none',
            title: '确认人不能重复',
            duration: 1500
          });
          return;
        }
      }

      item.searchPerson = user.DEPT_POST_NAME;
      item.DEPARTMENT_ID = user.DEPARTMENT_ID || '';
      item.DEPARTMENT_NAME = user.DEPARTMENT_NAME || '';
      item.USER_ID = user.USER_ID || '';
      item.USER_NAME = user.NAME || '';

      this.closePersonPopup();
    },
    filterConfirmUser(index) {
      const query = this.measuresListCopy[index].searchConfirmUser.trim().toLowerCase();
      if (!query) {
        this.measuresListCopy[index].filteredConfirmUsers = this.measuresListCopy[index].userList;
        this.measuresListCopy[index].USER_ID = ''
        this.measuresListCopy[index].USER_NAME = ''
      } else {
        this.measuresListCopy[index].filteredConfirmUsers = this.measuresListCopy[index].userList.filter(user =>
            user.NAME.toLowerCase().includes(query)
        );
      }
    },
    toggleConfirmDropdown(index) {
      if (!this.measuresListCopy[index].DEPARTMENT_ID) {
        uni.showToast({
          icon: 'none',
          title: '请选择确认单位',
          duration: 1500
        });
        return;
      }
      this.measuresListCopy[index].showAnalyzeDropdown = !this.measuresListCopy[index].showAnalyzeDropdown;
      if (this.measuresListCopy[index].showAnalyzeDropdown) this.filterConfirmUser(index);
    },
    selectConfirmUser(user,index) {
      for (let j = 0; j < this.measuresListCopy.length; j++) {
        if (this.measuresListCopy[j].USER_ID === user.USER_ID && index !== j) {
          uni.showToast({
            icon: 'none',
            title: '确认人不能重复',
            duration: 1500
          });
          return;
        }
      }
      this.measuresListCopy[index].searchConfirmUser = user.NAME;
      this.measuresListCopy[index].USER_ID =user.USER_ID;
      this.measuresListCopy[index].USER_NAME =user.NAME;
      this.measuresListCopy[index].showAnalyzeDropdown = false;
    },
    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
            });
          }
        }
      });
    },
    addMeasuresListCopy() {
      this.measuresListCopy.push({
        id: Math.random(),
        DEPARTMENT_ID: '',
        DEPARTMENT_NAME: '',
        USER_ID: '',
        USER_NAME: '',
        userList: [],
        userIndex: -1,
        selectMeasures: [],
        showAnalyzeDropdown: false,
        filteredConfirmUsers: [],
        searchConfirmUser: '',
        searchPerson: ''  // 新增字段
      })
    },
    removeMeasuresListCopy(index) {
      this.measuresListCopy.splice(index, 1)
    },
    fnSelectMeasures(index) {
      this.selectMeasuresShow = true
      this.selectMeasuresIndex = index
    },

    showDeptTree(index) {
      this.isUps = true
      this.$refs['tkiTree' + index][0]._show();
    },

    deptTreeConfirm(e, i) {
      this.isUps = false;
      this.measuresListCopy[i].DEPARTMENT_ID = e[0].id;
      this.measuresListCopy[i].DEPARTMENT_NAME = e[0].name;
      this.measuresListCopy[i].USER_ID = ''
      this.measuresListCopy[i].USER_NAME = ''
      this.measuresListCopy[i].searchConfirmUser = ''
      this.getUserList(e[0].id, i);
    },

    deptTreeCancel(e) {
      this.isUps = false;
    },

    pickerUser(e, i) {
      for (let j = 0; j < this.measuresListCopy.length; j++) {
        if (this.measuresListCopy[j].USER_ID === this.measuresListCopy[i].userList[e.detail.value].USER_ID && i !== j) {
          uni.showToast({
            icon: 'none',
            title: '确认人不能重复',
            duration: 1500
          });
          return;
        }
      }
      this.measuresListCopy[i].userIndex = e.detail.value;
      this.measuresListCopy[i].USER_ID = this.measuresListCopy[i].userList[e.detail.value].USER_ID;
      this.measuresListCopy[i].USER_NAME = this.measuresListCopy[i].userList[e.detail.value].NAME;
      this.$forceUpdate();//强制刷新
    },

    isBlankList(i) {
      if (this.measuresListCopy[i].userList.length == 0) {
        uni.showToast({
          icon: 'none',
          title: '请先选择确认单位',
          duration: 1500
        })
      }
    },

    goSubmit(APPLY_STATUS) {
      var _this = this;
      if (_this.imgList.length <= 0) {
        uni.showToast({
          icon: 'none',
          title: '请签字',
          duration: 1500
        });
        return;
      }
      if (APPLY_STATUS == 1) {
        for (let i = 0; i < this.measuresListCopy.length; i++) {
          const measures = this.measuresListCopy[i]
          if (!measures.USER_ID) {
            uni.showToast({
              icon: 'none',
              title: '第' + (i + 1) + '项未设置确认人',
              duration: 1500
            });
            return;
          }
          if (measures.selectMeasures.length === 0) {
            uni.showToast({
              icon: 'none',
              title: '第' + (i + 1) + '项未选择安全措施',
              duration: 1500
            });
            return;
          }
        }

      }
      var files = [];
      var signtime = [];
      var signers = [];
      if (APPLY_STATUS == 1) {
        for (let i = 0; i < this.measuresListCopy.length; i++) {
          const measures = this.measuresListCopy[i]
          for (let j = 0; j < measures.selectMeasures.length; j++) {
            signers.push({
              BUS_BLINDBOARD_MEASURES_ID: measures.selectMeasures[j].BUS_BLINDBOARD_MEASURES_ID,
              USER_ID: measures.USER_ID
            })
          }
        }
        if (signers.length !== this.measuresList.length) {
          uni.showToast({
            icon: 'none',
            title: '请为每个安全措施选择确认人',
            duration: 1500
          });
          return;
        }
      }
      this.uploadImgFaults(files, signtime)
      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;
            }
            const formData = {}
            uni.showLoading({
              title: '请稍候'
            })
            formData.BLINDBOARD_ID = _this.pd.BLINDBOARD_ID
            formData.SIGNTIME = signtime.join(",")
            formData.USER_ID = loginUser.USER_ID
            formData.APPLY_STATUS = APPLY_STATUS
            formData.PREPARERS = JSON.stringify(signers)
            formData.STEP_REASON = res.content ? res.content : ''
            uni.uploadFile({
              url: basePath + 'app/blindboard/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
                });
              }
            })
          }
        }
      })
    },

    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)
      })
    },

    getMeasures() {
      var _this = this;
      uni.request({
        method: 'POST',
        dataType: 'json',
        header: {
          'Content-type': 'application/x-www-form-urlencoded'
        },
        url: basePath + '/app/blindboard/listAllMeasures?tm=' + new Date().getTime(),
        data: {
          CORPINFO_ID: loginUser.CORPINFO_ID,
          USER_ID: loginUser.USER_ID,
        },
        success: function (res) {
          _this.measuresList = res.data.measuresList.map((item, index) => {
            item.userList = []
            item.userIndex = -1
            return item
          })
        }
      });
    },

    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, 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) {
            _this.measuresListCopy[i].userList = res.data.userList;
          } else {
            uni.showToast({
              title: res.data.message,
              duration: 2000
            });
          }
        }
      })
    },

    /*
       *手写板
       */
    showModal(e) {
      this.modalName = e.currentTarget.dataset.target
    },
    hideModal(e) {
      this.modalName = null
    },
    DelImg(index) {
      this.imgList.splice(index, 1)
    },
    //完成
    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();
    },
  }
}
</script>

<style>
.measures {
  padding-left: 16px;
  padding-right: 16px;

  .title {
    font-weight: bold;
    color: #000000;
    font-size: 14px;
  }

  .content {
    font-size: 14px;
    color: #000000;
    margin-top: 5px;
    margin-bottom: 5px;
  }
}

.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;
}

.dropdown view {
  padding: 8px 10px;
  cursor: pointer;
}

.dropdown view:hover {
  background: #f5f5f5;
}
.search-input {
  position: relative;
  display: flex;
  align-items: center;
  border-radius: 4px;
  padding: 0 10px;
  height: 40px;
}

.search-icon {
  position: absolute;
  right: 10px;
  font-size: 18px;
  color: #666;
}

.cuIcon-right {
  position: absolute;
  right: -12px;
  top: -10px;
}

.cuIcon-right:before {
  content: "\e6a3";
  color: #999;
}

.showbg {
  position: absolute;
  top: 45px;
  left: 0;
  background: #ffffff;
  line-height: 2.6;
  width: 100%;
  padding: 5px;
  border: 1px solid #eeeeee;
  border-radius: 4px;
  z-index: 999;
}

.list-item {
  padding: 14px 12px;
  border-bottom: 1px solid #9f9e9e;
  font-size: 28upx;
  color: #333;
}

</style>
