<template>
  <view>
    <cu-custom bgColor="bg-gradual-blueness" :isBack="true" :isRingt="true">
      <block slot="backText">返回</block>
      <block slot="content">隐患延期整改详情</block>
    </cu-custom>
    <view>
      <hiddenView :hidden_id="this.HIDDEN_ID"/>
    </view>
    <view v-if="sq == '0' || sq == '-1' ">
      <view class="wui-form-list">
        <view class="wui-sub-title">
          <text>{{ sq == '0' ? "延期整改申请" : "延期整改审批" }}</text>
        </view>
        <view v-if="sq == '0'">
          <view class="cu-form-group margin-top">
            <view class="title">申请延期日期</view>
            <picker mode="date" :value="DELAY_TIME" :start="rectifyPlanCompletionStartTime"
                    @change="changeDate">
              <view class="picker">
                {{ DELAY_TIME ? DELAY_TIME : '请选择' }}
              </view>
            </picker>
          </view>
          <view class="cu-form-textarea margin-top">
            <view class="cu-form-title">延期期间防范措施</view>
            <textarea maxlength="-1" v-model="DISPOSAL_PLAN"
                      placeholder="请对延期期间防范措施进行详细描述(必填项)"></textarea>
          </view>
          <view class="cu-form-textarea margin-top" style="border-top: none">
            <view class="cu-form-title">延期原因</view>
            <textarea maxlength="-1" v-model="EXAMINE" placeholder="请对延期原因进行详细描述(必填项)"></textarea>
          </view>
          <view class="cu-form-group bb-default">
            <view class="title">延期审核部门</view>
            <view class="picker-tree-box">
              <view class="picker-tree" @tap="showZgTree">
                {{ DELAYCHECKDEPTNAME ? DELAYCHECKDEPTNAME : '请选择' }}
              </view>
            </view>
            <tki-tree ref="tkiTree"
                      :selectParent=true
                      :range="treeNode"
                      rangeKey="name"
                      @confirm="zgtreeDelayCheck"></tki-tree>
          </view>
          <view class="cu-form-group bb-default">
            <view class="title">延期审核人</view>
            <view style="position: relative">
              <view class="search-input">
                <input
                    type="text"
                    style="text-align: right"
                    v-model="searchDelayCheckUser"
                    placeholder="请输入延期审核人"
                    @input="filterDelayCheckUser"
                    @click="toggleDelayCheckDropdown"
                >
                <view class="search-icon" @click="toggleDelayCheckDropdown">
                  <text class="cuIcon-right"></text>
                </view>
              </view>
              <view v-show="showDelayCheckDropdown" class="showbg" style="position: absolute; left: 0; top: 36px;">
                <view
                    v-for="(user, index) in filteredDelayCheckUsers"
                    :key="index"
                    @click="selectDelayCheckUser(user)"
                >
                  {{ user.NAME }}
                </view>
              </view>
            </view>
          </view>
        </view>
        <view v-if="sq == '-1'">
          <view class="cu-form-group bb-default">
            <view class="title text-hui">处置方式</view>
            <radio-group class="selected">
              <view class="group mr20">
                <radio class='radio' value="1" :checked="ISQUALIFIED==='2'" @click="radio('2')"></radio>
                <text>通过</text>
              </view>
              <view class="group">
                <radio class='radio' value="0" :checked="ISQUALIFIED==='1'" @click="radio('1')"></radio>
                <text>拒绝</text>
              </view>
            </radio-group>
          </view>
          <view class="cu-form-textarea">
            <view class="cu-form-title">处置意见</view>
            <textarea maxlength="-1" @input="textareaAInput" placeholder="请对处置意见进行详细描述(必填项)"></textarea>
          </view>
        </view>
      </view>
      <view class="padding flex flex-direction bf">
        <button :loading="buttonloading" class="cu-btn bg-green margin-tb-sm lg" @click="goSubmit">提交</button>
      </view>
    </view>

  </view>
</template>

<script>
import {
  basePath, corpinfoId, formatDate, loginSession, loginUser
} from '@/common/tool.js';
import tkiTree from "@/components/select-tree/select-tree.vue"
import hiddenView from '@/components/hidden_view/index.vue';

export default {
  components: {
    tkiTree,
    hiddenView
  },
  data() {
    return {
      HIDDEN_ID: "",
      ISQUALIFIED: "2",
      HIDDENDESCR: "",
      REPULSE_CAUSE: "",
      DISPOSAL_PLAN: "",
      EXAMINE: "",
      HIDDENEXAMINE_ID: "",
      DELAY_TIME: "",
      rectifyPlanCompletionStartTime: '',
      // 申请为0 审批为1
      sq: "",
      DELAYCHECKOR: "",
      DELAYCHECKORNAME: "",
      DELAYCHECKDEPTNAME: "",
      DELAY_CHECK_DEPT: "",
      RECTIFICATIONDEADLINE: "",
      buttonloading: false,
      delayCheckUserList: [],
      treeNode: [],
      showDelayCheckDropdown: false,
      filteredDelayCheckUsers: [],
      searchDelayCheckUser: '',
    }
  },
  onLoad(e) {
    console.log(e)
    this.HIDDEN_ID = e.id;
    this.sq = e.sq;
    this.DELAY_TIME = e.DELAY_TIME;
    this.HIDDENEXAMINE_ID = e.HIDDENEXAMINE_ID;
    this.RECTIFICATIONDEADLINE = e.RECTIFICATIONDEADLINE;
    this.rectifyPlanCompletionStartTime = this.RECTIFICATIONDEADLINE;
    this.getDept();
    loginSession();
  },
  watch: {
    treeNode: function(newVal) {
      // 当 treeNode 更新后尝试设置默认选中项
      this.setDefaultDeptSelection();
    }
  },
  onReady() {
  },
  onShow() {

  },
  methods: {
    // 显示树形选择器
    showZgTree() {
      this.$refs.tkiTree._show();
    },
    // 确定回调事件
    zgtreeDelayCheck(e) {
      this.DELAY_CHECK_DEPT = e[0].id;
      this.DELAYCHECKDEPTNAME = e[0].name;
      this.searchDelayCheckUser = '';
      this.uindex = -1;
      this.DELAYCHECKOR = '';
      this.DELAYCHECKORNAME = '';
      this.$forceUpdate(); //强制刷新
      this.getUserList(this.DELAY_CHECK_DEPT);
    },
    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);
            // _this.other[0].DEPARTMENT_ID = loginUser.DEPARTMENT_ID;
            // _this.other[0].DEPARTMENT_NAME = loginUser.DEPARTMENT_NAME;
            // _this.other[0].USER_ID = loginUser.USER_ID;
            // _this.other[0].USER_NAME = loginUser.NAME;
          } else {
            uni.showToast({
              title: res.data.message,
              duration: 2000
            });
          }
        }
      });
    },
    //获取人员列表
    getUserList(DEPARTMENT_ID, 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: DEPARTMENT_ID,
          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.otherUserList[i] = [];
              _this.otherUserList[i] = res.data.userList;
              _this.$forceUpdate(); //强制刷新
            } else {
              _this.delayCheckUserList = res.data.userList;
            }
          } else {
            uni.showToast({
              title: res.data.message,
              duration: 2000
            });
          }
        }
      })
    },
    filterDelayCheckUser() {
      const query = this.searchDelayCheckUser.trim().toLowerCase();
      if (!query) {
        this.filteredDelayCheckUsers = this.delayCheckUserList;
        this.DELAYCHECKOR = '';
        this.DELAYCHECKORNAME = '';
      } else {
        this.filteredDelayCheckUsers = this.delayCheckUserList.filter(user =>
            user.NAME.toLowerCase().includes(query)
        );
      }
    },
    toggleDelayCheckDropdown() {
      if (!this.DELAY_CHECK_DEPT) {
        uni.showToast({
          icon: 'none',
          title: '请选择延期审核部门',
          duration: 1500
        });
        return;
      }
      if (!this.delayCheckUserList.length) {
        uni.showToast({
          icon: 'none',
          title: '部门下无延期审核人',
          duration: 1500
        });
        this.searchDelayCheckUser = ""
        return;
      }
      this.showDelayCheckDropdown = !this.showDelayCheckDropdown;
      if (this.showDelayCheckDropdown) this.filterDelayCheckUser();
    },
    selectDelayCheckUser(user) {
      this.searchDelayCheckUser = user.NAME;
      this.DELAYCHECKOR = user.USER_ID;
      this.DELAYCHECKORNAME = user.NAME;
      this.showDelayCheckDropdown = false;
    },
    setDefaultDeptSelection() {
      if (this.treeNode && this.pd.DELAYCHECKDEPTNAME) {
        const findNode = (nodes, name) => {
          for (let node of nodes) {
            if (node.name === name) {
              return node;
            }
            if (node.children) {
              const found = findNode(node.children, name);
              if (found) return found;
            }
          }
          return null;
        };

        const selectedNode = findNode(this.treeNode, this.pd.DELAYCHECKDEPTNAME);
        if (selectedNode) {
          this.pd.DELAY_CHECK_DEPT = selectedNode.id;
          this.pd.DELAYCHECKDEPTNAME = selectedNode.name;
          selectedNode.checked = true;
          this.getUserList(selectedNode.id); // 获取对应部门人员列表
          this.$forceUpdate(); //强制刷新
        }
      }
    },
    textareaAInput(e) {
      this.REPULSE_CAUSE = e.detail.value
    },
    radio(e) {
      this.ISQUALIFIED = e
    },
    changeDate(e) {
      this.DELAY_TIME = e.detail.value
      this.$forceUpdate();//强制刷新
    },
    goSubmit() {
      let _this = this
      console.log(this.sq)
      if (this.sq == '0') {
        if (!_this.DELAY_TIME) {
          uni.showToast({
            icon: 'none',
            title: '请选择延期日期',
            duration: 1500
          });
          return;
        }
        if (!_this.DISPOSAL_PLAN) {
          uni.showToast({
            icon: 'none',
            title: '请填延期期间防范措施',
            duration: 1500
          });
          return;
        }
        if (!_this.EXAMINE) {
          uni.showToast({
            icon: 'none',
            title: '请填写延期原因',
            duration: 1500
          });
          return;
        }
        if (!this.DELAY_CHECK_DEPT) {
          uni.showToast({
            icon: 'none',
            title: '请填写延期审核部门',
            duration: 1500
          });
          return;
        }
        if (!this.DELAYCHECKOR) {
          uni.showToast({
            icon: 'none',
            title: '请填写延期审核人',
            duration: 1500
          });
          return;
        }
        this.buttonloading = false
        uni.request({
          url: basePath + '/app/hidden/extensionHidden',
          method: 'POST',
          dataType: 'json',
          header: {
            'Content-type': 'application/x-www-form-urlencoded'
          },
          data: {
            HIDDEN_ID: _this.HIDDEN_ID,
            IS_EXTENSION: 1,
            DELAY_TIME: _this.DELAY_TIME,
            DISPOSAL_PLAN: _this.DISPOSAL_PLAN,
            RECTIFICATIONDEADLINE: _this.RECTIFICATIONDEADLINE,
            EXAMINE: _this.EXAMINE,
            RECTIFICATIONDEPT: loginUser.DEPARTMENT_ID,
            RECTIFICATIONOR: loginUser.USER_ID,
            DELAY_CHECK_DEPT: _this.DELAY_CHECK_DEPT,
            DELAY_CHECK_USER: _this.DELAYCHECKOR,
            CORPINFO_ID: loginUser.CORPINFO_ID,
            USER_ID: loginUser.USER_ID,
          },
          success: (res) => {
            this.buttonloading = false
            if ("success" == res.data.result) {
              uni.showToast({
                icon: 'none',
                title: '申请成功！',
                duration: 1500
              });
              setTimeout(function () {
                var pages = getCurrentPages(); // 获取当前页面栈
                var prePage = pages[pages.length - 2]; // 上一个页面
                prePage.$vm.initflag = true; // A 页面 init方法 为true
                uni.navigateBack({});
                uni.hideLoading();
              }, 1500);
            } else {
              uni.showToast({
                title: res.data.msaesge,
                duration: 2000
              });
            }
          }
        });
      }
      if (this.sq == '-1') {
        if (!_this.REPULSE_CAUSE) {
          uni.showToast({
            icon: 'none',
            title: '请填写处置意见',
            duration: 1500
          });
          return;
        }
        this.buttonloading = false
        uni.request({
          url: basePath + '/app/hidden/setHiddenDangerDelayApproval',
          method: 'POST',
          dataType: 'json',
          header: {
            'Content-type': 'application/x-www-form-urlencoded'
          },
          data: {
            HIDDEN_ID: _this.HIDDEN_ID,
            HIDDENEXAMINE_ID: _this.HIDDENEXAMINE_ID,
            DELAY_TIME: _this.DELAY_TIME,
            REPULSE_CAUSE: _this.REPULSE_CAUSE,
            STATE: _this.ISQUALIFIED,
            DEPARTMENT_ID: loginUser.DEPARTMENT_ID,
            CORPINFO_ID: loginUser.CORPINFO_ID,
            USER_ID: loginUser.USER_ID,
          },
          success: (res) => {
            this.buttonloading = false
            if ("success" == res.data.result) {
              uni.showToast({
                icon: 'none',
                title: _this.ISQUALIFIED === '2' ? '延期申请通过！' : '延期申请不通过！',
                duration: 1500
              });
              setTimeout(function () {
                var pages = getCurrentPages(); // 获取当前页面栈
                var prePage = pages[pages.length - 2]; // 上一个页面
                prePage.$vm.initflag = true; // A 页面 init方法 为true
                uni.navigateBack({});
                uni.hideLoading();
              }, 1500);
            } else {
              uni.showToast({
                title: res.data.msaesge,
                duration: 2000
              });
            }
          }
        });
      }
    }
  }
}
</script>
<style>


.selected {
  display: flex;
  align-items: center;
}

.selected .radio {
  transform: scale(0.75);
  margin-right: 10upx;
}

.bf .cu-btn {
  border-radius: 0;
  width: 100%;
  height: 84upx;
  font-weight: bold;
}

.group {
  display: flex;
  align-items: center;
}

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

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

.cu-form-textarea {
  background-color: #ffffff;
  padding: 1upx 30upx 20upx;
  min-height: 100upx;
}

.cu-form-textarea textarea {
  height: 4.6em;
  width: 100%;
  line-height: 1.2em;
  flex: 1;
  font-size: 28upx;
  padding: 0;
}

.cu-form-title {
  padding: 20upx 0;
}

.cuIcon-right {
  position: absolute;
  right: -12px;
  top: -10px;
}
</style>
