<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 margin-top">
            <view class="title">选择延期审核人</view>
            <view class="picker" @click="openPersonPopup" style="font-size: 28upx; flex: 1; display: flex; align-items: center; justify-content: flex-end; padding-right: 20upx;">
              {{ searchPerson || '请选择延期审核人' }}
              <text class="cuIcon-right" style="margin-left: 10upx;"></text>
            </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="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: '',
      // ... 其他数据
      searchPerson: '',           // 显示在表单中的值
      personPopupShow: false,     // 控制弹窗显示
      popupSearch: '',            // 弹窗内的搜索关键词
      filteredPopupList: [],      // 弹窗内过滤后的人员列表
      personList: []
    }
  },
  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: {
    openPersonPopup() {
      // 提取括号前的名字
      this.popupSearch = this.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 => {
          // 安全处理：将 undefined 转换为空字符串
          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 => {
          // 安全处理：将 undefined 转换为空字符串
          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) {
      this.searchPerson = user.DEPT_POST_NAME;
      this.DELAYCHECKOR = user.USER_ID || '';
      this.DELAY_CHECK_DEPT = user.DEPARTMENT_ID || '';
      this.DELAYCHECKORNAME = user.DEPT_POST_NAME; // 保留完整信息用于提交
      this.closePersonPopup();
    },
    // 显示树形选择器
    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;
}

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

</style>
