<template>
  <view class="zhixing-container" style="margin: 20rpx;margin-top: 220rpx; min-height: 300px; ">
    <view class="zhixing_top" style="display: flex; flex-direction: column;">
      <view style="display: flex; flex-direction: row;margin-bottom: 10px; margin-left: 10px;">
        <view class="querybox">
          <view class="querybox_title" style="display: flex; flex-direction: row;">
            <view style="color: #ca4341; margin-right:5px;">*</view>
            <view>项目编号：</view>
          </view>
          <!-- <combox-more style="width:150px;" @onSelect="banhaoselectionEvent" label=""></combox-more> -->
          <!-- <piaoyi-select style="300px" :inputValue.sync="queryParams.projectId" ref="piaoyiSelect" :clearable="true"
            :filterable="true" placeholder="请选择项目编号" valueKey="projectId" label="lablename" :options="xmdwlist"
            @changeval="halechange">
          </piaoyi-select> -->
          <!-- 项目自定义选择器组件 -->
          <view @click="xmpickerVisible = true; hideKeyboard()">
            <u-input style="width: 400px;" v-model="queryParams.projectname" disabled disabledColor="#ffffff"
              placeholder="请选择项目编号"></u-input>
          </view>

        </view>
        <view class="querybox">
          <u-button style="width:100px; float: left;margin-left: 20px;" type="primary" icon="search" text="查询"
            @click="getlistinfo()"></u-button>
        </view>

      </view>
      <view style="margin-top: 20px; margin-bottom: 20px;">
        <u-button style="width:100px; float: left; margin-left:10px;" type="success" icon="plus-circle" text="添加检查点"
          :disabled="activenum>=2" @click="addjiancha()"></u-button>
        <u-button style="width:100px; float: left;margin-left: 20px;" type="primary" icon="edit-pen" text="编辑检查点"
          :disabled="activenum!=1||!isbutclick" @click="upjiancha()"></u-button>
        <u-button style="width:100px; float: left;margin-left: 20px;" type="error" icon="trash" text="删除检查点"
          :disabled="activenum!=1||!isbutclick" @click="shanchujiancha()"></u-button>
        <u-button style="width:100px; float: left;margin-left: 20px;" type="warning" icon="info-circle" text="变更历史"
          @click="biangenls()" :disabled="activenum!=1||!isbutclick"></u-button>
        <u-button style="width:100px; float: left;margin-left: 20px;" type="primary" icon="list-dot" text="评价表"
          :disabled="!queryParams.projectId" @click="pingjia()"></u-button>
      </view>
    </view>

    <view class="zhixing_center">
      <!--     <u-table2 ref="pageTable" border :data="columns1" :columns="tableData1" @selection-change="handleSelectionChange"
        maxHeight="500" :span-method="spanMethod">
      </u-table2> -->
      <!-- :span-method="spanMethod" -->
      <uni-table border ref="pageTable" style="width:98%; margin: 0 auto; max-height:450px;" type="selection"
        @selection-change="handleSelectionChange" emptyText="暂无数据	">
        <uni-tr class="frisytr" style="background-color: #f5f5f5;">
          <uni-th align="center" width="150">专业</uni-th>
          <uni-th align="center" width="150">单项</uni-th>
          <uni-th align="center" width="200">子项</uni-th>
          <uni-th align="center" width="200">要素</uni-th>
          <uni-th align="center" width="150">风险等级</uni-th>
          <uni-th align="center" width="150">检查点位</uni-th>
          <uni-th align="center" width="120">是否存在问题</uni-th>
          <uni-th align="center" width="200">问题描述</uni-th>
          <uni-th align="center" width="120">问题图片</uni-th>
          <uni-th align="center" width="120">得分</uni-th>
          <uni-th align="center" width="120">制单</uni-th>
          <uni-th align="center" width="200">创建时间</uni-th>
        </uni-tr>
        <uni-tr v-for="(item, index) in tableData" :key="index">
          <uni-td align="center">{{item.name1}}</uni-td>
          <uni-td>{{item.name2}}</uni-td>
          <uni-td :rowspan="2">{{item.name3}}</uni-td>
          <uni-td>{{item.name4}}</uni-td>
          <uni-td align="center">
            {{item.riskLevel=='1'?'A':item.riskLevel=='2'?'B':item.riskLevel=='3'?'C':''}}
          </uni-td>
          <uni-td>{{item.checkPoint}}</uni-td>
          <uni-td align="center">
            {{item.result=='1'?'符合':item.result=='2'?'不符合':item.result=='3'?'不涉及':''}}
          </uni-td>
          <uni-td>{{item.issue}}</uni-td>
          <uni-td @click="showimg(item)" align="center">
            <view style="text-align: center; justify-content: center;"> <u-text align="center" type="primary"
                :text="item.imgNum" v-if="item.imgNum" style=" margin: 0 auto;"></u-text></view>
          </uni-td>
          <uni-td align="center">{{item.score}}</uni-td>
          <uni-td align="center">{{item.createBy}}</uni-td>
          <uni-td align="center">{{item.createTime?$dayjs(item.createTime).format("YYYY-MM-DD HH:mm:ss"):''}}</uni-td>
        </uni-tr>

      </uni-table>
      <view style="width:98%; margin: 0 auto; text-align: center; line-height:40px;">小计：{{statistic}} </view>
    </view>
    <u-modal content="" :closeOnClickOverlay="true" title="图片预览" confirmText="关闭" width="600px" :show="imgboxshow"
      @confirm="() => imgboxshow = false">
      <view class="slot-content" style="width: 100%;min-height: 200px; max-height: 200px; overflow-y: auto;">
        <u-album :urls="imgurlslist" style="margin-top: 20px;" autoWrap showMore multipleSize="100"></u-album>
      </view>

    </u-modal>


    <u-modal content="" :closeOnClickOverlay="true" title="变更历史" confirmText="关闭" width="600px" :show="biangenshow"
      @confirm="() => biangenshow = false">
      <view class="slot-content biangengcontent" style="width: 100%;">
        <scroll-view scroll-y="true" style="height: 300px;">
          <view style="display: flex;
    flex-direction: column;
width: 100%;align-items: left; border-top:1px solid #eee;">
            <!--   <u-steps direction="column">
            <u-steps-item v-for="(item,index) in bglslist" :key="index" :title="item.info" :desc="item.createTime">
            </u-steps-item>
          </u-steps> -->
            <uni-steps :options="bglslist" style="color: #999;" :active="bglslist.length" active-color="#007AFF"
              direction="column" />
          </view>
        </scroll-view>
      </view>
    </u-modal>

    <u-modal content="" :closeOnClickOverlay="true" :title="pjmodaltitle" confirmText="关闭" width="800px"
      :show="pjmodalshow" @confirm="() => pjmodalshow = false">
      <view class="slot-content" style="width: 100%;">

        <scroll-view scroll-y="true" style="height: 300px;">
          <view style="display: flex;
        flex-direction: column;
    width: 100%;   align-items: left; border-top:1px solid #eee;">
            <uni-table border ref="page1Table" style="width:98%; margin: 0 auto; ">
              <uni-tr style="background-color: #f5f5f5;">
                <uni-th align="center">序号</uni-th>
                <uni-th align="center">评价内容</uni-th>
                <uni-th align="center">得分</uni-th>
              </uni-tr>
              <uni-tr v-for="(item, index) in pjtableInfolist" :key="index">
                <uni-td align="center">{{Number(index+1)}}</uni-td>
                <uni-td align="center">
                  {{item.info}}
                </uni-td>
                <uni-td align="center">
                  {{item.score}}
                </uni-td>
              </uni-tr>
            </uni-table>
          </view>
        </scroll-view>
      </view>
    </u-modal>
    <customPicker :visible="xmpickerVisible" title="选择项目编号" :options="xmpickerConfig.options"
      :displayKey="xmpickerConfig.displayKey" :valueKey="xmpickerConfig.valueKey" :multiple="xmpickerConfig.multiple"
      :searchable="xmpickerConfig.searchable" :value="xmpickerConfig.value" @confirm="xmhandleConfirm"
      @cancel="xmhandleCancel" />
    <UniMenu />
  </view>
</template>

<script>
  import {
    getsafety_hazardInfo,
    getxmdwdefaultconditionlist,
    getloginfo,
    delsafety_hazard
  } from "@/apis/zhixing"
  import {

    getevaluationIdinfo
  } from "@/apis/wenjuan"
  import UniMenu from '@/components/uni-menu/uni-menu.vue'
  import comboxMore from '@/components/wl-combox-more/combox-more.vue'
  import useUserStore from '@/store/user';
  import CustomPicker from '@/components/custom-search-picker/index.vue';
  export default {
    components: {
      UniMenu,
      comboxMore,
      CustomPicker
    },
    data() {
      return {
        // upurl: import.meta.env.VITE_APP_BASE_PRE + '/safety_hazard/table/img',
        //  httpurl: import.meta.env.VITE_APP_BASE_PRE,
        //  upurl: 'http://219.146.89.198:19388' + '/safety_hazard/table/img',
        // httpurl: 'http://219.146.89.198:19380/prod-api',
        userStore: useUserStore(),
        xmpickerVisible: false,
        isbutclick: false,
        xmpickerConfig: {
          title: '选择项目',
          options: [],
          displayKey: 'lablename',
          valueKey: 'projectId',
          multiple: false,
          searchable: true,
          value: ''
        },
        statistic: '',
        columns1: [{
            id: 1,
            name: '苹果',
            amount: 10,
            date: '2023-01-01'
          },
          {
            id: 2,
            name: '苹果',
            amount: 15,
            date: '2023-01-01'
          },
          {
            id: 3,
            name: '香蕉',
            amount: 8,
            date: '2023-01-02'
          },
          {
            id: 4,
            name: '香蕉',
            amount: 12,
            date: '2023-01-02'
          }
        ],
        columns: [{
            type: 'selection',
            width: '50px',
            align: 'center'
          },

          {
            title: '项目编号',
            key: 'projectName',
            align: 'center',
          },
          {
            title: '专业',
            key: 'name1',
            align: 'center'
          },
          {
            title: '单项',
            key: 'name2',
            align: 'center'
          },
          {
            title: '子项',
            key: 'name3',
            align: 'center'
          },
          {
            title: '要素',
            key: 'name4',
            align: 'center'
          },
          {
            title: '检查点位',
            key: 'checkPoint',
            align: 'center'
          },
          {
            title: '是否存在问题',
            key: 'result',
            align: 'center',

          },
          {
            title: '问题描述',
            key: 'issue',
            align: 'center'
          },
          {
            title: '问题图片',
            key: 'imgNum',
            align: 'center',

          },
          {
            title: '得分',
            key: 'score',
            align: 'center',

          },
          {
            title: '制单',
            key: 'createTime',
            align: 'center',


          },
          {
            title: '创建时间',
            key: 'createBy',
            align: 'center',

          },
        ],
        biangenshow: false,
        imgboxshow: false,
        imgurlslist: [],
        tableData1: [{
            type: 'selection',
            width: '50px',
            align: 'center'
          }, {
            title: 'ID',
            key: 'id'
          },
          {
            title: '姓名',
            key: 'name'
          },
          {
            title: '数量',
            key: 'amount'
          },
          {
            title: '日期',
            key: 'date'
          }
        ],
        tableData: [],
        bglslist: [],
        queryParams: {
          // pageNum: 1,
          // pageSize: 10,
          projectId: null,
          projectname: '',
          reasonable: false,
        },
        infolist: [],
        activeitem: null,
        activenum: 0,
        pjmodaltitle: '非火灾高危单位',
        pjmodalshow: false,
        pjtableInfolist: [],
        xmdwlist: [
          //   {
          //   projectId: 0,
          //   projectNo: "001",
          //   customerCompany3Name: "撒大苏打",
          //   lablename: "001（撒大苏打）",
          // }, {
          //   projectId: 1,
          //   projectNo: "002",
          //   customerCompany3Name: "法国",
          //   lablename: "002（法国）",
          // },

        ],
      }
    },
    computed: {
      nick() {
        // debugger
        // return  userStore.username
        const userStore = useUserStore();
        return userStore.name
      },
      imageSrc() {

        const userStore = useUserStore();
        return userStore.avatar
      },

      username() {
        // debugger
        // return  userStore.username
        const userStore = useUserStore();
        return userStore.username
      },
      avatar() {
        //debugger
        const userStore = useUserStore();
        return userStore.avatar
      },
      windowHeight() {
        return uni.getSystemInfoSync().windowHeight - 50
      }
    },
    // // 监听页面返回
    // onBackPress() {
    //   //debugger
    //   uni.redirectTo({
    //     url: '/pages/index/index'
    //   });
    //   // 阻止界面返回默认操作， 这一步主要是为了防止界面出现异常，uniapp有对onBackPress的详细讲解
    //   return true;
    // },

    onShow() {
      // this.getlistinfo(); //获取检查列表
      this.getxmdwlist(); //获取项目单位列表
      const userStore = useUserStore();
      userStore.setparentmenutitle('执行');
      userStore.setchildrenmenutitle('检查表');
    },
    onLoad() {
      // this.getUser()
    },
    methods: {
      // 单元格合并方法
      // const spanMethod = (data) => {

      // };

      spanMethod(data) {
        const {
          row,
          column,
          rowIndex,
          columnIndex
        } = data;

        // 合并第一列(姓名)中相同内容的单元格
        if (columnIndex === 1) {
          if (rowIndex === 0 || rowIndex === 1) {
            if (rowIndex === 0) {
              return [2, 1]; // 合并2行1列
            } else {
              return [0, 0]; // 隐藏该单元格
            }
          } else


          if (rowIndex === 2 || rowIndex === 3) {
            if (rowIndex === 2) {
              return [2, 1]; // 合并2行1列
            } else {
              return [0, 0]; // 隐藏该单元格
            }
          }
        }

        // 合并第三列(日期)中相同内容的单元格
        if (columnIndex === 3) {
          if (rowIndex === 0 || rowIndex === 1) {
            if (rowIndex === 0) {
              return [2, 1]; // 合并2行1列
            } else {
              return [0, 0]; // 隐藏该单元格
            }
          } else if (rowIndex === 2 || rowIndex === 3) {
            if (rowIndex === 2) {
              return [2, 1]; // 合并2行1列
            } else {
              return [0, 0]; // 隐藏该单元格
            }
          }
        }
        // if (columnIndex > 1) {
        //   //第一列
        //   //  debugger
        //   let spanArr = this.getSpanArr(this.columns1, column.key);
        //   const _row = spanArr[rowIndex];
        //   const _col = _row > 0 ? 1 : 0;
        //   return [_row, _col]
        //   // {
        //   //   rowspan: _row,
        //   //   colspan: _col,
        //   // };
        // }



        //  return [0, 0]; // 隐藏该单元格
      },


      getSpanArr(data, spanKey) {
        // debugger
        // 处理合并行的数据
        let spanArr = [];
        let pos = "";
        for (let i = 0; i < data.length; i++) {
          if (i === 0) {
            spanArr.push(1);
            pos = 0;
          } else {
            // 判断当前元素与上一个元素是否相同
            if (data[i][spanKey] === data[i - 1][spanKey]) {
              spanArr[pos] += 1;
              spanArr.push(0);
            } else {
              spanArr.push(1);
              pos = i;
            }
          }
        }
        return spanArr;
      },



      pingjia() {
        getevaluationIdinfo(this.queryParams.projectId).then((res) => {
          //  debugger
          this.pjtableInfolist = []
          this.highRiskFlag = res.data.highRiskFlag;
          this.pjtableInfolist = res.data.tableInfo || [];


          if (this.highRiskFlag) {
            this.pjmodaltitle = '火灾高危单位';
          } else {
            this.pjmodaltitle = '非火灾高危单位';
          }

          this.pjmodalshow = true;
        });

      },
      getbglslist() {
        //获取变更历史
        getloginfo(this.activeitem.checkTableId).then((res) => {
          //debugger
          this.biangenshow = true;
          // this.bglslist = res.rows;
          res.rows = res.rows || [];
          for (let s of res.rows) {
            s.title = s.info + ` -（${s.createBy}）`;
            s.desc = s.createTime ? this.$dayjs(s.createTime).format("YYYY-MM-DD HH:mm:ss") : '';

          }
          this.bglslist = res.rows;
        })
      },

      hideKeyboard() {
        uni.hideKeyboard()
      },
      xmhandleConfirm(result) {
        // 处理确认项目
        //  debugger
        // console.log(result);
        this.xmpickerConfig.value = result.selectedValue;
        this.queryParams.projectname = result.selectedItem.lablename;
        this.queryParams.projectId = result.selectedItem.projectId;
        this.xmpickerVisible = false;
        this.getlistinfo(); //查询列表
      },
      xmhandleCancel() {
        // 处理取消项目
        this.xmpickerVisible = false
      },
      biangenls() {
        //变更历史
        this.getbglslist();
        //获取变更历史

      },
      showimg(item) {
        if (!item.imgNum) return;
        this.imgurlslist = [];
        if (item.imgUrl.includes(',')) {
          // debugger
          // this.imgurlslist = item.imgUrl.split(",");
          let imglist = item.imgUrl.split(",");
          for (let s of imglist) {
            //this.imgurlslist.push(this.httpurl + s);
            this.imgurlslist.push(this.userStore.allurl + s);

          }
          // this.imgurlslist = imglist;
        } else {
          //this.imgurlslist = [this.httpurl + item.imgUrl]
          this.imgurlslist = [this.userStore.allurl + item.imgUrl]
        }
        // debugger
        this.imgboxshow = true;

      },

      addjiancha() {
        //新增
        if (this.activeitem) {
          uni.navigateTo({
            url: `/pages/zhixing/addjianchabiao?isedit=0&projectid=${this.queryParams.projectId}&projectName=${this.queryParams.projectname}&checkTableId=${this.activeitem.checkTableId}&id1=${this.activeitem.standardCheckTable1Id}&id2=${this.activeitem.standardCheckTable2Id}&id3=${this.activeitem.standardCheckTable3Id}&id4=${this.activeitem.standardCheckTable4Id}`,
          })
        } else {
          uni.navigateTo({
            url: `/pages/zhixing/addjianchabiao?isedit=0&projectid=${this.queryParams.projectId}&projectName=${this.queryParams.projectname}`,
          })
        }

      },
      upjiancha() {
        //编辑
        uni.navigateTo({
          url: `/pages/zhixing/addjianchabiao?isedit=1&projectid=${this.activeitem.projectId}&checkTableId=${this.activeitem.checkTableId}&id1=${this.activeitem.standardCheckTable1Id}&id2=${this.activeitem.standardCheckTable2Id}&id3=${this.activeitem.standardCheckTable3Id}&id4=${this.activeitem.standardCheckTable4Id}&projectName=${this.queryParams.projectname}`,
        })
      },
      shanchujiancha() {
        //删除
        this.$modal.confirm('确定要删除此条信息吗？').then(() => {
          // debugger
          delsafety_hazard(this.activeitem.checkTableId).then((res) => {
            //  debugger
            this.$modal.msgSuccess("删除成功！");
            this.getlistinfo(); //获取检查列表
          })
        });
      },
      clearSelection() {
        //清空选中项
        //  this.$refs.pageTable?.clearSelection();
        this.activeitem = null;
        this.activenum = 0;

      },
      handleSelectionChange(selection) {
        return;
        // debugger
        // let del_row = selection.shift();
        // this.$refs.pageTable.toggleRowSelection(del_row, false);

        // console.log('当前选中的行:', JSON.stringify(selection));
        //this.$refs.pageTable.toggleAllSelection(false);
        //  this.$refs.pageTable.clearSelection();
        // this.$refs.pageTable.toggleRowSelection(selection.index, true);
        this.activenum = selection.detail.index.length;
        if (selection.detail.index.length > 1) {
          // debugger
          this.$modal.msgError("只能选一个！");
          this.activeitem = null;
          // this.$refs.pageTable.toggleRowSelection(selection.detail.index[selection.detail.index.length - 1], false);
          // this.$refs.pageTable.toggleAllSelection(true);
          // this.$refs.pageTable.clearSelection();
          return;
        }
        if (selection.detail.index.length == 0) {
          this.activeitem = null;
          this.isbutclick = false;
        } else {
          this.activeitem = this.tableData[selection.detail.index[selection.detail.index.length - 1]];
        }
        if (this.activeitem) {
          //debugger
          if (this.activeitem.checkTableId == null) {
            this.isbutclick = false;
          } else {
            this.isbutclick = true;
          }
        }



        // this.$refs.pageTable.clearSelection();

      },
      getlistinfo() {
        //获取检查列表
        this.clearSelection(); //清空
        //  this.queryParams.projectname = null;
        getsafety_hazardInfo(this.queryParams).then((res) => {
          //debugger
          this.tableData = res.rows || [];
          this.statistic = res.statistic;
        })
      },
      getxmdwlist() {
        //获取项目单位列表
        getxmdwdefaultconditionlist().then((res) => {
          //debugger

          for (let s of res.data.projects) {
            s.lablename = s.projectNo + `（${s.customerCompany3Name}）`;
          }
          this.xmdwlist = res.data.projects || [];

          this.xmpickerConfig.options = res.data.projects || [];
          if (this.xmdwlist.length > 0) {
            //debugger
            this.queryParams.projectId = this.xmdwlist[0].projectId;
            this.queryParams.projectname = this.xmdwlist[0].lablename;
            this.xmpickerConfig.value = this.xmdwlist[0].projectId;
          }

          this.getlistinfo(); //获取检查列表
        })
      },

      halechange() {
        //查询  
        this.getlistinfo(); //获取检查列表
      },
      banhaoselectionEvent(selection, selectObj) {
        console.log('selectionEvent:', selection, selectObj)
      }
    }
  }
</script>

<style lang="scss" scoped>
  .zhixing_top {
    width: 100%;
    display: flex;
    flex-direction: column;

    .querybox {
      display: flex;
      flex-direction: row;
      align-items: center;

      .querybox_title {}
    }
  }

  ::v-deep .infotable {
    // width: 300px;

    .xincellclass {}

    .u-table-header {
      z-index: 0;
    }

    .u-table-cell {
      .u-table-cell_content {
        padding: 0rpx 16rpx 0rpx 16rpx;
        white-space: normal;
        text-align: left;

      }
    }
  }


  ::v-deep .uni-table {
    // tr:first-child {
    //   th:nth-of-type(1) {

    //     /* 你的样式 */
    //     .uni-table-checkbox {
    //       display: none !important;
    //     }

    //     //
    //   }

    // }
    .frisytr {
      .uni-table-checkbox {
        display: none !important;
      }
    }

    .checkbox__inner {
      z-index: 0 !important;
    }
  }

  ::v-deep .biangengcontent {
    .uni-steps__column-title {
      color: #666 !important;
    }

    .uni-steps__column-desc {
      color: #666 !important;
    }
  }
</style>