<template>
  <div class="quicl-review" @scroll="handleScroll">
    <el-image-viewer v-if="showViewer" :on-close="closeViewer" :url-list="viewerList" />
    <div class="card-container">
      <p>
        <el-button type="primary" @click="backPage" style="width: 80px">返回</el-button>
      </p>
    </div>
    <div class="card-container">
      <div class="search-content">
        <el-form :model="form" label-width="100px" ref="formRef">
          <el-row>
            <el-col :span="6">
              <el-form-item label="任务ID" prop="taskId">
                <el-input v-model="form.taskId" placeholder="执行任务" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="任务编号" prop="taskNumber">
                <el-input v-model="form.taskNumber" placeholder="任务编号" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="服务类型" prop="taskTypeId">
                <el-select v-model="form.taskTypeId" placeholder="服务类型" class="w100" clearable>
                  <el-option :label="item.taskTypeName" :value="item.id" v-for="item in taskList" :key="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="起止时间">
                <ElQuarterPicker placeholder="请选择" v-model="monthrange" @change="monthrangeChange" class="w100" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="执行包名称" prop="pkgName">
                <el-input v-model="form.pkgName" placeholder="执行包名称" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="生产企业" prop="mahName">
                <el-select v-model="form.mahName" placeholder="生产企业" clearable class="w100">
                  <el-option :label="item.label" :value="item.value" v-for="item in mahNameList" :key="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="代表名字" prop="memberName">
                <el-input v-model="form.memberName" placeholder="代表名字" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <div class="search-btns">
                <el-button type="primary" @click="onSubmit">查询</el-button>
                <el-button type="primary" @click="restFn">重置</el-button>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>

    <div class="card-container" v-if="!IS_FWS && type">
      <div class="review-btns">
        <el-button type="primary" class="all-btn" @click="allPassClick">批量审核</el-button>
        <el-checkbox v-model="allCheck" @change="allClick">全选</el-checkbox>
      </div>
    </div>

    <div class="card-list card-container" v-loading="getPageLoading" :style="{ height: cardContainerheight, overflow: 'hidden' }">
      <template v-if="noData">
        <div class="no-data">
          <el-empty description="暂无数据"></el-empty>
        </div>
      </template>
      <div class="cards" style="width: 100%" v-else>
        <template v-for="(item, index) in list">
          <div class="card" :key="index" v-if="item.show" :style="{ left: item.left, top: item.top }" :class="'cls' + item.id">
            <div class="task-info">
              <div class="task-type-info">
                <el-checkbox
                  v-if="!IS_FWS && type"
                  v-model="item.checked"
                  @change="
                    (val) => {
                      itemChecked(val, item.id, item.score);
                    }
                  "
                ></el-checkbox>
                服务类型： {{ getName(item.taskType) }}
              </div>
            </div>
            <div class="info">
              <p>任务ID：{{ item.id }}</p>
              <p>任务编号：{{ item.taskInfo.taskNumber }}</p>
            </div>
            <div class="info">
              <p>服务积分：{{ item.score }}</p>
              <p>代表姓名：{{ item.taskUserName }}</p>
            </div>
            <div class="info">
              <p>产品名称：{{ item.drugName }}</p>
              <p>生产企业：{{ item.mah }}</p>
            </div>
            <div class="info">
              <p>执行包名称：{{ item.pkgName }}</p>
              <p>起止时间：{{ item.period }}</p>
            </div>
            <div class="info">
              <p>服务供应商公司名称：{{ item.deptName }}</p>
            </div>
            <div class="detail">服务详情</div>
            <template v-if="item.config && item.config.length != 0">
              <div class="field-box" v-for="iten in item.config" :key="iten.id">
                <template v-if="iten.taskFiledType == 'domain' || iten.taskFiledType == 'select'">
                  <div class="title-value">{{ iten.taskFiledValue }}：</div>
                  <div class="desc-value" v-show="!(iten.taskTypeId == '19' && iten.taskFiledKey == 'temp3')">
                    {{ getDesc(iten, item) }}
                  </div>
                </template>
                <!-- * 文本类型 -->
                <template v-if="typeArr.includes(iten.taskFiledType)">
                  {{ item.taskFiledType }}
                  <div class="title-value">{{ iten.taskFiledValue }}：</div>
                  <div class="desc-value">
                    {{ item?.wmTaskContent[iten?.taskFiledKey] || '--' }}
                  </div>
                </template>
                <div v-if="iten.taskFiledType == 'img'" class="divline"></div>
                <!-- 图片上传 -->
                <template v-if="iten.taskFiledType == 'img'">
                  <div class="upload-field">
                    <div class="field-text" :class="{ required: iten.isMustfill == '1' }">
                      {{ iten.taskFiledValue }}：
                      <!-- {{ getImgList(item.wmTaskContent[iten.taskFiledKey], iten) }} -->
                    </div>
                    <!-- 上传组件 -->
                    <div class="img-box" v-if="iten.imgList">
                      <div v-for="(iiten, index) in iten.imgList" :key="index" class="img-box-content">
                        <span class="type">{{ iiten.type }}</span>
                        <img :src="iiten.url" @click="viewImgFn(iiten.url)" class="img-iten" alt="" />
                      </div>
                    </div>
                  </div>
                </template>
                <!-- 长文本 -->
                <template v-if="iten.taskFiledType == 'longtext'">
                  <div class="longtext-box">
                    <div class="field-text" :class="{ required: iten.isMustfill == '1' }">{{ iten.taskFiledValue }}：</div>
                    <textarea class="textarea-box" :disabled="true" :value="item.wmTaskContent[iten.taskFiledKey] || '--'" :maxlength="iten.taskFiledMaxsize" />
                  </div>
                </template>
              </div>
            </template>

            <template>
              <div class="reason" v-if="item.supervisionMessage">
                <div class="reason-list">
                  <span>监督员监督结果</span>
                  <div class="text">{{ item.supervisionMessage }}</div>
                </div>
              </div>
            </template>
            <template>
              <div class="reason" v-if="item.adviceMessages && item.adviceMessages.length">
                <div class="reason-list" v-for="(iten, indey) in item.adviceMessages" :key="indey">
                  <div class="text">{{ iten }}</div>
                </div>
              </div>
            </template>
            <template v-if="!IS_FWS && type">
              <div class="reason">
                <div class="field-text">监督结果</div>
                <el-input type="textarea" v-model="item.submitRemark"></el-input>
              </div>
            </template>
            <div class="btns" v-if="!IS_FWS && type">
              <el-button class="btn" type="danger" @click="passClick(index, false, item.id, item)">不同意</el-button>
              <el-button class="btn" type="primary" @click="passClick(index, true, item.id, item)">同意</el-button>
            </div>
          </div>
        </template>
      </div>
    </div>
    <!-- 批量审核弹窗 -->
    <el-dialog title="批量审核" :visible.sync="dialogVisible" width="45%" center :before-close="handleClose">
      <el-form ref="allFormRef" :model="taskForm" label-width="120px" :rules="rules">
        <el-form-item label="审批意见:" prop="supervision" class="formitem-box">
          <el-radio-group v-model="taskForm.supervision">
            <el-radio :label="true">同意</el-radio>
            <el-radio :label="false">不同意</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="意见说明:"
          prop="remarks"
          class="formitem-box"
          :rules="[
            {
              required: taskForm.supervision == false,
              message: '请输入审批说明',
              trigger: 'blur'
            }
          ]"
        >
          <el-input type="textarea" v-model="taskForm.remarks"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="sureBtn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { supervisionTaskListApi, supervisionTaskCreateApi, supervisionCreateBatchApi } from '@/api/monitor.js';
import { getTaskList } from '@/api/assignPoints/currency/taskAudit';
import ElImageViewer from 'element-ui/packages/image/src/image-viewer';
import { mapGetters } from 'vuex';
import ElQuarterPicker from '@/components/ElQuarterPicker/index';
import { getDictType } from '@/api/common';

import { debounce } from '@/util/util';
export default {
  components: { ElImageViewer, ElQuarterPicker },
  data() {
    return {
      typeArr: ['area', 'text', 'inputautoselect', 'map', 'mapwithimg', 'datetime', 'datatimerange', 'money', 'number', ''],
      type: 0,
      hasMap: false,
      mapShow: true,
      taskList: [],
      baseUrl: process.env.VUE_APP_URL,
      list: [],
      mahNameList: [],
      checkedIds: [],
      mapIds: [],
      maps: {},
      column1Height: 400,
      column2Height: 400,
      imgTypeList: ['jpeg', 'jpg', 'png', 'git', 'bmp'], // 能查看的文件类型
      showViewer: false,
      viewerList: [],
      IS_FWS: false,
      page: {
        total: 0,
        currentPage: 1, // 当前页数
        pageSize: 10 // 每页显示多少条
      },
      form: {
        taskId: '',
        taskNumber: '',
        taskTypeId: '',
        pkgName: '',
        pkgPeriod: [],
        mahName: '',
        memberName: ''
      },
      monthrange: '',
      allCheck: false,
      checkedIds: [],
      dialogVisible: false,
      taskForm: {
        supervision: null,
        remarks: ''
      },
      rules: {
        supervision: [{ required: true, message: '请选择审批意见', trigger: 'change' }]
      },
      getPageLoading: false,
      noData: false,
      cardContainerheight: ''
    };
  },
  computed: {
    ...mapGetters(['userInfo', 'roles'])
  },
  async created() {
    this.type = this.$route.query.type == 0;

    await this.getTaskList();
    this.getList();
  },
  beforeDestroy() {
    this.mapShow = false;
  },
  mounted() {
    if (this.userInfo.roles.includes(37)) {
      this.IS_FWS = true;
    }
  },

  methods: {
    handleScroll(event) {
      const scrollHeight = event.target.scrollHeight; // 获取滚动元素的总高度
      const scrollTop = event.target.scrollTop; // 获取滚动元素的当前滚动高度
      const windowHeight = event.target.clientHeight; // 获取滚动元素的可视区域高度
      if (scrollTop + windowHeight >= scrollHeight - 10) {
        if (!this.getPageLoading && this.page.total > this.page.currentPage * this.page.pageSize) {
          this.page.currentPage += 1;
          this.getList();
        }
      }
    },
    allClick(val) {
      this.checkedIds = [];
      if (val) {
        this.checkedIds = [];
        this.list.forEach((item) => {
          item.checked = true;
          this.checkedIds.push(item.id);
        });
      } else {
        this.checkedIds = [];
        this.allCheck = false;
        this.list.forEach((item) => {
          item.checked = false;
        });
      }
    },
    allPassClick() {
      if (!this.checkedIds.length) {
        return this.$message.info('请选择待审核数据');
      }
      this.dialogVisible = true;
    },
    itemChecked(val, id, score) {
      if (val) {
        this.checkedIds.push(id);
      } else {
        let index = this.checkedIds.findIndex((item) => item === id);
        this.checkedIds.splice(index, 1);
      }
    },
    handleClose() {
      this.taskForm = {
        supervision: null,
        remarks: ''
      };
      this.dialogVisible = false;
    },

    sureBtn: debounce(function () {
      this.$refs.allFormRef.validate((valid) => {
        if (valid) {
          let args = {
            supervisionIds: this.checkedIds,
            supervision: this.taskForm.supervision,
            remarks: this.taskForm.remarks
          };
          supervisionCreateBatchApi(args)
            .then((res) => {
              if (res.data.code === 0) {
                this.handleClose();
                this.$message.success('批量审核成功');
                this.list.forEach((item) => {
                  if (item.checked) {
                    item.checked = false;
                    item.allCheck = false;
                    item.show = false;
                  }
                });
                this.checkedIds = [];
                this.$forceUpdate();
                this.waterfallFlowCalculation();
              }
            })
            .catch(() => {
              this.tableLoading = false;
            });
        }
      });
    }, 500),

    monthrangeChange(e) {
      if (e) {
        let arr = this.getQuarterRange(e);
        this.form.pkgPeriod = arr;
      } else {
        this.monthrange = '';
        this.form.pkgPeriod = [];
      }
    },
    getQuarterRange(dateString) {
      const [year, quarterCode] = dateString.split('-').map(Number);
      let startMonth, endMonth, endDay;
      switch (quarterCode) {
        case 1: // Q1
          startMonth = 1;
          endMonth = 3;
          endDay = 31;
          break;
        case 2: // Q2
          startMonth = 4;
          endMonth = 6;
          endDay = 30;
          break;
        case 3: // Q3
          startMonth = 7;
          endMonth = 9;
          endDay = 30;
          break;
        case 4: // Q4
          startMonth = 10;
          endMonth = 12;
          endDay = 31;
          break;
        default:
          throw new Error('Invalid quarter code');
      }
      const startDate = `${year}-${String(startMonth).padStart(2, '0')}-01`;
      const endDate = `${year}-${String(endMonth).padStart(2, '0')}-${endDay}`;
      return [startDate, endDate];
    },
    onSubmit() {
      this.page = {
        total: 0,
        currentPage: 1, // 当前页数
        pageSize: 10 // 每页显示多少条
      };
      this.list = [];
      this.getList();
    },
    closeViewer() {
      this.showViewer = false;
    },
    viewImgFn(url) {
      this.viewerList = [url];
      this.showViewer = true;
    },

    backPage() {
      this.$router.$avueRouter.closeTag();
      this.$router.back();
    },

    async getTaskList() {
      let res;
      res = await getTaskList(this.$route.query.deptId, this.$route.query.taskStatus == '2' ? '2' : '');
      this.taskList = res.data.data;
      getDictType({ type: 'mah_name' }).then((res) => {
        this.mahNameList = res.data.data;
      });
    },

    getName(taskType) {
      let curr = this.taskList.find((item) => item.id == taskType);
      return curr.taskTypeName;
    },

    restFn() {
      this.$refs.formRef.resetFields();
      this.monthrange = '';
      this.form.pkgPeriod = [];
    },
    async getList() {
      this.getPageLoading = true;
      let obj = Object.assign(
        {
          deptId: this.$route.query.deptId,
          current: this.page.currentPage,
          size: this.page.pageSize,
          review: !this.type
        },
        this.form
      );

      let res = await supervisionTaskListApi(obj);
      if (res.data.code == 0) {
        this.page.total = res.data.data.total;
        let list = res.data.data.records;
        list.forEach((item) => {
          item.show = true;
          item.submitRemark = '';
          item.checked = false;
          item?.config?.forEach((iten) => {
            iten.taskFiledType = iten.taskFiledType.trim();
            if (iten.taskFiledType == 'img') {
              this.getImgList(item.wmTaskContent[iten.taskFiledKey], iten);
            }
          });
        });
        this.list.push(...list);

        if (this.list.length == 0) {
          this.noData = true;
        } else {
          this.noData = false;
        }
        this.$forceUpdate();
        this.getPageLoading = false;
        this.$nextTick(() => {
          this.waterfallFlowCalculation();
        });
      }
    },
    waterfallFlowCalculation() {
      let column1Height = 20;
      let column2Height = 20;
      let top = 0;
      let left = 0;
      this.list.forEach((item) => {
        if (item.show) {
          const currEle = document.querySelector('.cls' + item.id);
          if (!currEle) return;
          let eleHeight = currEle.clientHeight;
          if (column1Height <= column2Height) {
            top = column1Height;
            column1Height += eleHeight + 20;
            left = '1%';
          } else {
            top = column2Height;
            column2Height += eleHeight + 20;
            left = '51%';
          }
          item.top = top + 'px';
          item.left = left;
        }
      });
      this.cardContainerheight = column1Height > column2Height ? column1Height + 'px' : column2Height + 'px';
      this.$forceUpdate();
    },
    getDesc(item, curr) {
      // 拜访类任务
      const arr = ['51', '52', '53'];
      if (arr.includes(item.taskTypeId) && item.taskFiledKey === 'temp24') {
        return curr.wmTaskContent['temp24label'];
      }
      // 获取需要转换的字符串（例如 '1,2,3'）
      const contentValue = curr.wmTaskContent[item.taskFiledKey];
      if (!contentValue) return '--';
      // 获取字典表对应数组
      const itemList = curr.dict[item.dictGroupName] || [];
      // 按逗号拆分成数组
      const valueArray = contentValue.split(',');
      // 将每个拆分值找到对应的 label
      const result = valueArray.map((val) => {
        const foundItem = itemList.find((dictItem) => dictItem.value === val);
        return foundItem ? foundItem.label : null;
      });
      // 如果有任意一个值无法找到对应的 label，则直接返回 '--'
      if (result.some((label) => label === null)) {
        return '--';
      }
      // 否则，使用逗号拼接并返回
      return result.join(',');
    },

    getImgList(urlStr, item) {
      // 如果类型不匹配或者 urlStr 为空，直接返回
      if (item.taskFiledType !== 'img' || !urlStr) return '';

      // 缓存环境变量中的基础 URL
      const { VUE_APP_URL } = process.env;

      // 以逗号分割，并过滤掉空字符串
      const imgArray = urlStr.split(',').filter(Boolean);
      if (!imgArray.length) return '';

      // 生成包含 type 和 url 的数组
      const imgList = imgArray.map((originalUrl) => {
        let type = '无';
        let url = originalUrl;

        if (url.includes(';1')) {
          type = '拍照';
          url = url.replace(';1', '');
        } else if (url.includes(';2')) {
          type = '相册';
          url = url.replace(';2', '');
        }

        return {
          type,
          url: VUE_APP_URL + url
        };
      });

      // 提取预览图片的 URL 列表
      const previewList = imgList.map((item) => item.url);

      // 将处理结果赋值给对应字段
      item.imgList = imgList;

      item.previewList = previewList;

      // 函数约定返回空字符串
      return '';
    },

    passClick: debounce(function (index, type, id, item) {
      if (this.debounceTimer) return;
      this.debounceTimer = setTimeout(() => {
        this.debounceTimer = null;
      }, 500);

      if (!type && !item.submitRemark) {
        return this.$message.info('请填写异常原因');
      }
      let remarks = item.submitRemark ? item.submitRemark : '监督无异常';
      let obj = {
        taskId: id,
        pkgId: item.taskInfo.scorePackageId,
        supervision: type,
        remarks: remarks
      };
      supervisionTaskCreateApi(obj)
        .then(() => {
          this.list[index].show = false;
          this.list[index].checked = false;
          this.$forceUpdate();
          this.waterfallFlowCalculation();
        })
        .catch((error) => {
          console.error('Error:', error);
        });
    }, 500)
  }
};
</script>

<style lang="scss" scoped>
.quicl-review {
  overflow: auto;
  height: 100%;
  padding-bottom: 30px;
  .card-container {
    margin: 0 10px;
    margin-bottom: 10px;
    padding: 20px;
    border-radius: 10px;
    background: #fff;
    box-sizing: border-box;
  }
}

.search-btns {
  margin-left: 50px;
  width: 150px;
  display: flex;
  justify-content: space-between;
}

.card-list {
  overflow: auto;
  min-height: 200px;
  box-sizing: border-box;
  .cards {
    box-sizing: border-box;
    width: 100%;
    padding: 10px;
    position: relative;
    min-height: 600px;
  }

  .card {
    position: absolute;
    box-sizing: border-box;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.2);
    border: 1px solid #ebeef5;
    background-color: #fff;
    color: #303133;
    transition: 0.3s;
    min-height: 300px;
    width: 48%;
    // min-width: 500px;
    margin-bottom: 10px;
    padding: 10px;

    .reason {
      padding: 0 10px 5px;
      .reason-list {
        margin-bottom: 6px;
        .text {
          margin: 5px 0;
          font-size: 14px;
          color: #e93d3d;
        }
      }
    }
  }

  .task-type-info {
    font-size: 16px;
    color: #333;
    font-weight: 600;
    margin-bottom: 5px;
  }
  .info {
    display: flex;
    font-size: 12px;
    color: #7f7f7f;
    margin-bottom: 5px;

    p {
      flex: 1;
      margin-right: 30px;
    }
  }

  .detail {
    font-size: 14px;
    font-weight: 500;
    color: #333333;
    border-bottom: 2px solid #d7d6d5;
    line-height: 30px;
    margin: 5px 0;
  }
}

.field-box {
  padding: 0 10px 5px;
  overflow: hidden;
  .title-value {
    //width: 50%;
    float: left;
  }
  .desc-value {
    float: left;
  }
  .upload-field {
    .img-box {
      padding-top: 5px;
      display: flex;
    }
    .file-box {
      .file-item {
        padding: 2px 8px;
        cursor: pointer;
        &:hover {
          background-color: #f5f7fa;
          color: #2d8cf0;
        }
      }
    }
  }
  .img-box-content {
    padding-top: 15px;
    position: relative;
    .type {
      font-size: 12px;
      position: absolute;
      top: 0;
    }
  }
  .img-item {
    width: 100px;
    height: 100px;
    margin-right: 5px;
  }

  .divline {
    width: 100%;
    height: 5px;
    background-color: #e9e9e9;
    margin-bottom: 5px;
  }
  .img-iten {
    height: 60px;
    margin-right: 5px;
    width: 50px;
    cursor: pointer;
  }
}

.longtext-box {
  .textarea-box {
    margin-top: 5px !important;
    width: 100%;
    padding: 3px;
  }
}

.no-data {
  margin: 0 auto;
}

.btns {
  padding: 0 20px;
  padding-top: 5px;
  display: flex;
  align-items: center;
  .btn {
    width: 48%;
  }
}

.all-btn {
  margin-right: 18px;
}

.card-all-review {
  width: 350px;
}

.teskDetailsty {
  width: 100%;
  height: 30px;
  line-height: 30px;
  font-size: 16px;
  font-weight: 600;
  color: #333333;
  border-bottom: 1px solid #d7d6d5;
  margin: 0 0 10px 0;
}
.check-btns {
  width: 150px;
  display: flex;
  justify-content: space-between;
}

.check-tips {
  margin-bottom: 5px;
  font-size: 16px;
  color: rgb(233 77 77);
  text-align: center;
  font-weight: 600;
}
</style>
