<template>
  <view>
    <cu-custom bgColor="bg-gradual-blueness" :isBack="true">
      <block slot="backText">返回</block>
      <block slot="content">隐患确认</block>
    </cu-custom>
    <view>
      <hiddenView :hidden_id="this.id"/>
    </view>
    <view class="wui-form-list">
      <view class="wui-sub-title">
        <text>隐患确认</text>
      </view>
      <view class="cu-form-textarea">
        <view class="cu-form-title">
          确认意见
        </view>
        <textarea :value="RECTIFY_ADVICE" maxlength="-1" @input="textareaAInput" placeholder=""></textarea>
      </view>
      <view v-if="pd.RECTIFICATIONTYPE == '2'">
<!--        <view class="cu-form-group bb-default">-->
<!--          <view class="title">整改期限</view>-->
<!--          <picker mode="date" :value="pd.RECTIFICATIONDEADLINE" :start="rectifyPlanCompletionStartTime" @change="changeDate">-->
<!--            <view class="picker">-->
<!--              {{ pd.RECTIFICATIONDEADLINE == '' ? '请选择' : pd.RECTIFICATIONDEADLINE }}-->
<!--            </view>-->
<!--          </picker>-->
<!--        </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">-->
<!--              {{ pd.RECTIFICATIONDEPTNAME ? pd.RECTIFICATIONDEPTNAME : '请选择' }}-->
<!--            </view>-->
<!--          </view>-->
<!--          <tki-tree ref="tkiTree"-->
<!--                    :selectParent=true-->
<!--                    :range="treeNode"-->
<!--                    rangeKey="name"-->
<!--                    @confirm="zgtreeConfirm"></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="searchRectificationUser"-->
<!--                  placeholder="请输入整改人"-->
<!--                  @input="filterRectificationUser"-->
<!--                  @click="toggleRectifyDropdown"-->
<!--              >-->
<!--              <view class="search-icon" @click="toggleRectifyDropdown">-->
<!--                <text class="cuIcon-right"></text>-->
<!--              </view>-->
<!--            </view>-->
<!--            <view v-show="showRectifyDropdown" class="showbg" style="position: absolute; left: 0; top: 36px;">-->
<!--              <view-->
<!--                  v-for="(user, index) in filteredRectificationUsers"-->
<!--                  :key="index"-->
<!--                  @click="selectRectificationUser(user)"-->
<!--              >-->
<!--                {{ user.NAME }}-->
<!--              </view>-->
<!--            </view>-->
<!--          </view>-->
<!--        </view>-->
      </view>
      <view v-else>
        <view class="cu-form-group bb-default">
          <view class="title">是否整改完成</view>
          <radio-group class="selected">
            <view class="group mr20">
              <radio class='radio' value="1" :checked="ISQUALIFIED==='1'" @click="radio('1')"></radio>
              <text>是</text>
            </view>
            <view class="group">
              <radio class='radio' value="2" :checked="ISQUALIFIED==='2'" @click="radio('2')"></radio>
              <text>否</text>
            </view>
          </radio-group>
        </view>
<!--        <view v-if="ISQUALIFIED==='2'" class="cu-form-group bb-default">-->
<!--          <view class="title"> {{rectifyPlanCompletionStartTime}}</view>-->
<!--          <picker mode="date" :value="pd.RECTIFICATIONDEADLINE" :start="rectifyPlanCompletionStartTime" @change="changeDate">-->
<!--            <view class="picker">-->
<!--              {{ pd.RECTIFICATIONDEADLINE == '' ? '请选择' : pd.RECTIFICATIONDEADLINE }}-->
<!--            </view>-->
<!--          </picker>-->
<!--        </view>-->
<!--        <view v-if="ISQUALIFIED==='2'" class="cu-form-group bb-default">-->
<!--          <view class="title">整改部门</view>-->
<!--          <view class="picker-tree-box">-->
<!--            <view class="picker-tree" @tap="showZgTree">-->
<!--              {{ pd.RECTIFICATIONDEPTNAME ? pd.RECTIFICATIONDEPTNAME : '请选择' }}-->
<!--            </view>-->
<!--          </view>-->
<!--          <tki-tree ref="tkiTree"-->
<!--                    :selectParent=true-->
<!--                    :range="treeNode"-->
<!--                    rangeKey="name"-->
<!--                    @confirm="zgtreeConfirm"></tki-tree>-->
<!--        </view>-->
<!--        <view v-if="ISQUALIFIED==='2'" 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="searchRectificationUser"-->
<!--                  placeholder="请输入整改人"-->
<!--                  @input="filterRectificationUser"-->
<!--                  @click="toggleRectifyDropdown"-->
<!--              >-->
<!--              <view class="search-icon" @click="toggleRectifyDropdown">-->
<!--                <text class="cuIcon-right"></text>-->
<!--              </view>-->
<!--            </view>-->
<!--            <view v-show="showRectifyDropdown" class="showbg" style="position: absolute; left: 0; top: 36px;">-->
<!--              <view-->
<!--                  v-for="(user, index) in filteredRectificationUsers"-->
<!--                  :key="index"-->
<!--                  @click="selectRectificationUser(user)"-->
<!--              >-->
<!--                {{ user.NAME }}-->
<!--              </view>-->
<!--            </view>-->
<!--          </view>-->
<!--        </view>-->
        <view v-if="ISQUALIFIED==='2'" 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>
    </view>
    <view class="padding flex flex-direction bf">
      <button :loading="buttonloading" class="cu-btn bg-green margin-tb-sm lg" @click="$noMultipleClicks(goSubmit)">确认
      </button>
      <button :loading="buttonloading" class="cu-btn bg-red margin-tb-sm lg" @click="$noMultipleClicks(fnRepulse)">打回
      </button>
    </view>
  </view>
</template>

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

export default {
  components: {
    hiddenView,
    tkiTree
  },
  data() {
    return {
      permissionID: '',
      rectifyPlanCompletionStartTime: "dsadsa",
      noClick: true,
      date: '',
      RECTIFY_ADVICE: '',
      RECTIFICATIONTIME: '',
      ISQUALIFIED: '1',
      buttonloading: false,
      imgList: [],
      imgList_plan: [],
      imgList_fa: [],
      id: '',
      pd: [],
      files: [],
      RECTIFYDESCR: '',
      basePath: basePath,
      baseImgPath: baseImgPath,
      HAVESCHEME: '0',
      HAVEPLAN: '0',
      HIDDENSCHEME_ID: '',
      treeNode: [], //部门下拉数据
      uindex: -1,
      IS_NORMAL: 1,
      rectificationUserList: [],
      other: [{
        "DEPARTMENT_ID": '',
        "USER_ID": '',
        "DEPARTMENT_NAME": '',
        "USER_NAME": '',
        index: -1
      }], //其他验收部门负责人员
      otherUserList: [],
      userpd: [],
      deppd: [],
      videoList: [],
      modalShow: false,
      videoSrc: '',
      library: false,
      showRectifyDropdown: false,
      filteredRectificationUsers: [],
      searchRectificationUser: '',
      // ... 其他数据
      searchPerson: '',           // 显示在表单中的值
      personPopupShow: false,     // 控制弹窗显示
      popupSearch: '',            // 弹窗内的搜索关键词
      filteredPopupList: [],      // 弹窗内过滤后的人员列表
      personList: []
    }
  },
  onLoad(e) {
    this.id = e.id;
    let now = new Date();
    var tomorrow = now.setDate(now.getDate() + 1);
    tomorrow = new Date(tomorrow);
    this.rectifyPlanCompletionStartTime = formatDate(tomorrow, 'yyyy-MM-dd');
    this.getData();
    this.getDept();
    loginSession();
  },
  watch: {
    treeNode: function(newVal) {
      // 当 treeNode 更新后尝试设置默认选中项
      this.setDefaultDeptSelection();
    }
  },
  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.pd.RECTIFICATIONOR = user.USER_ID || '';
      this.pd.RECTIFICATIONDEPT = user.DEPARTMENT_ID || '';
      this.pd.RECTIFICATIONORNAME = user.DEPT_POST_NAME; // 保留完整信息用于提交
      this.closePersonPopup();
    },
    filterRectificationUser() {
      const query = this.searchRectificationUser.trim().toLowerCase();
      if (!query) {
        this.filteredRectificationUsers = this.rectificationUserList;
        this.pd.RECTIFICATIONOR = '';
        this.pd.RECTIFICATIONORNAME = '';
      } else {
        this.filteredRectificationUsers = this.rectificationUserList.filter(user =>
            user.NAME.toLowerCase().includes(query)
        );
      }
    },
    toggleRectifyDropdown() {
      if (!this.pd.RECTIFICATIONDEPT) {
        uni.showToast({
          icon: 'none',
          title: '请选择整改部门',
          duration: 1500
        });
        return;
      }
      if (!this.rectificationUserList.length) {
        uni.showToast({
          icon: 'none',
          title: '部门下无整改人',
          duration: 1500
        });
        this.searchRectificationUser = ""
        return;
      }
      this.showRectifyDropdown = !this.showRectifyDropdown;
      if (this.showRectifyDropdown) this.filterRectificationUser();
    },
    selectRectificationUser(user) {
      this.searchRectificationUser = user.NAME;
      this.pd.RECTIFICATIONOR = user.USER_ID;
      this.pd.RECTIFICATIONORNAME = user.NAME;
      this.showRectifyDropdown = false;
    },
    textareaAInput(e) {
      this.RECTIFY_ADVICE = e.detail.value
    },
    fullScreenHandler(e) {
      if (uni.getSystemInfoSync().platform == "ios") {
        return
      }
    },
    getData() {
      var _this = this;
      uni.showLoading({
        title: '请稍候'
      })
      uni.request({
        url: basePath + '/app/hidden/goEdit',
        method: 'POST',
        dataType: 'json',
        header: {
          'Content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          HIDDEN_ID: _this.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
            if (_this.pd.HIDDENLEVEL == 'hiddenLevel0002') {
              _this.getqyData();
            }
            if (_this.pd.ISCONFIRM == '1') {
              _this.HAVESCHEME = '1'
            }
            for (let i = 0; i < res.data.hImgs.length; i++) {
              if (res.data.hImgs[i].FILEPATH.substring(res.data.hImgs[i].FILEPATH.lastIndexOf(".") + 1, res.data.hImgs[i].FILEPATH.length) === 'mp4') {
                _this.videoList.push(res.data.hImgs[i])
              } else {
                _this.files.push(res.data.hImgs[i])
              }
            }
            // _this.videoList = res.data.hiddenVideo
            // _this.files = res.data.hImgs;
            _this.other[0].DEPARTMENT_ID = _this.pd.HIDDENFINDDEPT;
            _this.other[0].DEPARTMENT_NAME = _this.pd.HIDDENFINDDEPTNAME;
            _this.other[0].USER_ID = _this.pd.CREATOR;
            _this.other[0].USER_NAME = _this.pd.CREATORNAME;
            this.getUserList(this.other[0].DEPARTMENT_ID, 0);
            this.$forceUpdate();//强制刷新
          } else if ("exception" == data.result) {
            uni.showToast({
              title: '错误',
              duration: 2000
            });
          }
        }
      });
    },
    getqyData() {
      var _this = this;
      uni.showLoading({
        title: '请稍候'
      })
      uni.request({
        url: basePath + '/app/corpinfo/goqyzzh',
        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) {
            uni.hideLoading();
            _this.userpd = res.data.userpd; //参数map
            _this.deppd = res.data.deppd; //参数map
            console.log(_this.pd.HIDDENLEVEL)
            if (_this.pd.HIDDENLEVEL == 'hiddenLevel0002') {
              _this.other[0].DEPARTMENT_ID = res.data.deppd.DEPARTMENT_ID;
              _this.other[0].DEPARTMENT_NAME = res.data.deppd.NAME;
              _this.other[0].USER_ID = res.data.userpd.USER_ID;
              _this.other[0].USER_NAME = res.data.userpd.USERNAME;


              console.log(_this.other)
            }
          } else if ("exception" == data.result) {
            uni.showToast({
              title: '错误',
              duration: 2000
            });
          }
        }
      });
    },

    //图片上传
    ChooseImage() {
      var _this = this;
      uni.chooseImage({
        count: 4, //默认9
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['camera', 'album'], //从相册选择
        success: (res) => {
          if (this.imgList.length != 0) {
            this.imgList = this.imgList.concat(res.tempFilePaths)
          } else {
            this.imgList = res.tempFilePaths
          }
        }
      });
    },
    ViewImage(e) {
      uni.previewImage({
        urls: this.imgList,
        current: e.currentTarget.dataset.url
      });
    },
    //图片上传
    ChooseImage_fa() {
      var _this = this;
      uni.chooseImage({
        count: 4, //默认9
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['camera', 'album'], //从相册选择
        success: (res) => {
          if (this.imgList_fa.length != 0) {
            this.imgList_fa = this.imgList_fa.concat(res.tempFilePaths)
          } else {
            this.imgList_fa = res.tempFilePaths
          }
        }
      });
    },
    fnRepulse() {
      var _this = this;
      // if (!this.RECTIFY_ADVICE) {
      //   uni.showToast({
      //     icon: 'none',
      //     title: '请填写确认意见',
      //     duration: 1500
      //   });
      //   return;
      // }
      uni.showModal({
        title: '确认打回隐患吗？',
        placeholderText: '请填写打回原因',
        cancelColor: "#000000",
        cancelText: '取消',
        editable: true,
        confirmText: '确定',
        success: res => {
          if (res.confirm) {
            if (!res.content) {
              uni.showToast({
                icon: 'none',
                title: '请填写打回原因',
                duration: 1500
              });
              return;
            }
            uni.showLoading({
              title: '请稍候'
            })
            uni.request({
              url: basePath + "/app/hidden/confirmRepulse", //提交接口
              method: 'POST',
              dataType: 'json',
              header: {
                'Content-type': 'application/x-www-form-urlencoded'
              },
              data: {
                RECTIFY_ADVICE: _this.RECTIFY_ADVICE,
                REPULSE_CAUSE: res.content,
                HIDDEN_ID: _this.id,
                CORPINFO_ID: loginUser.CORPINFO_ID,
                USER_ID: loginUser.USER_ID,
              },
              success: (res) => {
                uni.hideLoading();
                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: '错误',
                    duration: 2000
                  });
                }
              }
            });
            uni.hideLoading();
          }
        }
      })

    },
    async goSubmit() {
      // 整改类型   1 立即整改    2   限期整改
      if (this.pd.RECTIFICATIONTYPE == '2') {
        // if (!this.pd.RECTIFICATIONDEADLINE) {
        //   uni.showToast({
        //     icon: 'none',
        //     title: '请填写整改期限',
        //     duration: 1500
        //   });
        //   return;
        // }
        // if (!this.pd.RECTIFICATIONDEPT) {
        //   uni.showToast({
        //     icon: 'none',
        //     title: '请填写整改部门',
        //     duration: 1500
        //   });
        //   return;
        // }
        if (!this.pd.RECTIFICATIONOR) {
          uni.showToast({
            icon: 'none',
            title: '请选择整改人',
            duration: 1500
          });
          return;
        }
      }
      if (this.pd.RECTIFICATIONTYPE == '1' && this.ISQUALIFIED == '2') {
        // if (!this.pd.RECTIFICATIONDEADLINE) {
        //   uni.showToast({
        //     icon: 'none',
        //     title: '请填写整改期限',
        //     duration: 1500
        //   });
        //   return;
        // }
        // if (!this.pd.RECTIFICATIONDEPT) {
        //   uni.showToast({
        //     icon: 'none',
        //     title: '请填写整改部门',
        //     duration: 1500
        //   });
        //   return;
        // }
        if (!this.pd.RECTIFICATIONOR) {
          uni.showToast({
            icon: 'none',
            title: '请选择整改人',
            duration: 1500
          });
          return;
        }
      }
      let _this = this;
      uni.showLoading({
        title: '请稍候'
      })
      uni.request({
        url: basePath + "/app/hidden/confirmAdd", //提交接口
        method: 'POST',
        dataType: 'json',
        header: {
          'Content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          RECTIFICATIONTYPE: _this.pd.RECTIFICATIONTYPE,
          RECTIFICATIONDEPT: _this.pd.RECTIFICATIONDEPT,
          RECTIFICATIONOR: _this.pd.RECTIFICATIONOR,
          // RECTIFICATIONDEADLINE: _this.pd.RECTIFICATIONDEADLINE,
          ISQUALIFIED: _this.pd.ISQUALIFIED,
          RECTIFY_ADVICE: _this.RECTIFY_ADVICE,
          HIDDEN_ID: _this.id,
          CORPINFO_ID: loginUser.CORPINFO_ID,
          USER_ID: loginUser.USER_ID,
        },
        success: (res) => {
          uni.hideLoading();
          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: '错误',
              duration: 2000
            });
          }
        }
      });
    },
    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
            });
          }
        }
      });
    },
    // 确定回调事件
    zgtreeConfirm(e) {
      this.pd.RECTIFICATIONDEPT = e[0].id;
      this.pd.RECTIFICATIONDEPTNAME = e[0].name;
      this.searchRectificationUser = '';
      this.uindex = -1;
      this.pd.RECTIFICATIONOR = '';
      this.pd.RECTIFICATIONORNAME = '';
      this.$forceUpdate(); //强制刷新
      this.getUserList(this.pd.RECTIFICATIONDEPT);
    },
    // 显示树形选择器
    showZgTree() {
      this.$refs.tkiTree._show();
    },
    //获取人员列表
    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.rectificationUserList = res.data.userList;
            }
          } else {
            uni.showToast({
              title: res.data.message,
              duration: 2000
            });
          }
        }
      })
    },
    setDefaultDeptSelection() {
      if (this.treeNode && this.pd.RECTIFICATIONDEPTNAME) {
        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.RECTIFICATIONDEPTNAME);
        if (selectedNode) {
          this.pd.RECTIFICATIONDEPT = selectedNode.id;
          this.pd.RECTIFICATIONDEPTNAME = selectedNode.name;
          selectedNode.checked = true;
          this.getUserList(selectedNode.id); // 获取对应部门人员列表
          this.$forceUpdate(); //强制刷新
        }
      }
    },
    PickerZgr(e) {
      this.uindex = e.detail.value;
      this.pd.RECTIFICATIONOR = this.rectificationUserList[this.uindex].USER_ID;
      this.pd.RECTIFICATIONORNAME = this.rectificationUserList[this.uindex].NAME;
      this.$forceUpdate(); //强制刷新
    },
    PickerYsr(e, index) {
      this.other[index].index = e.detail.value;
      this.other[index].USER_ID = this.otherUserList[index][e.detail.value] ? this.otherUserList[index][e.detail.value].USER_ID : '';
      this.other[index].USER_NAME = this.otherUserList[index][e.detail.value] ? this.otherUserList[index][e.detail.value].NAME : '';

      for (let i = 0; i < this.other.length; i++) {
        if (i !== index && this.other[i].USER_ID === this.otherUserList[index][e.detail.value].USER_ID) {
          uni.showToast({
            title: '不能选择重复的验收部门负责人',
            icon: 'none',
            duration: 2000
          })
          this.other[index].index = ''
          this.other[index].USER_ID = ''
          this.other[index].USER_NAME = ''
          break
        }
      }
      this.$forceUpdate(); //强制刷新
    },
    radio(e) {
      this.ISQUALIFIED = e
    },
    changeDate(e) {
      this.pd.RECTIFICATIONDEADLINE = e.detail.value
    },
    ViewShowImage(e) {
      let files = [];
      for (var i = 0; i < this.files.length; i++) {
        files.push(baseImgPath + this.files[i].FILEPATH)
      }
      uni.previewImage({
        urls: files,
        current: e.currentTarget.dataset.index
      });
    },
    playVideo(e) {
      this.videoSrc = e.currentTarget.dataset.src
      this.modalShow = true
    },
    confirm({RECTIFYDESCR}) {
      this.RECTIFYDESCR = RECTIFYDESCR
    }
  }
}
</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;
}

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