<template>
	<div class="checkResult">
		<headNav
			@backPage="backPage"
			@addRoad="turnjudeg"
			:title="'检查总结'"
		></headNav>

		<!-- 检查结果 -->
		<div class="danger">
			<div class="headTip FontColorInfo">检查结果</div>

			<div class="noProblem" v-if="resultList.length === 0">
				检查项全部正常
			</div>
      <div class="noProblem colorRed"  v-else>
        检查项部分异常
      </div>
			<div class="dangerList" v-for="(item, index) in resultList" :key="index">
<!--				<div v-if="item.index === 1" class="index color1">1</div>-->
<!--				<div v-else-if="item.index === 2" class="index color2">2</div>-->
				<div class="index color3">{{ index+1 }}</div>
				<div class="flex1">
					<div class="dangerIistItem df jfsb aic">
             <div class="title">
               {{ item.item_type == "1" ? '其他' : (item.enforce_obj_class || item.enforce_class)}}
             </div>
            <div>
              <van-cell
                  :title="item.item_name"
                  is-link=""
                  @click="gotoDangerDetail(item)"
              ></van-cell>
            </div>
					</div>
          <div class="color3 mb10">
            {{item.item_content || item.enforce_content}}
          </div>
					<div class="dangerContent">
						<div class="df mb10">
							<div class="flex1">
								检查情况：
								<span class="FontColorError">异常</span>
							</div>
							<div class="flex1 OPoint">
								<span>{{ item.createdTime }}</span>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>

		<!-- 检查判断 -->
		<div class="checkJudge" v-if="hasRes">
			<div class="headTip FontColorInfo">检查判断</div>

			<div class="radio">
					<div class="radioItem">
						<div class="radioItem-name" @click="()=>checkChang('IMMEDIATELY')">
							<van-checkbox name="2" :value="!!checkRightNow.length" shape="square">部分检查情况异常，责令立即改正</van-checkbox>
							<div @click.stop="gotoList('IMMEDIATELY')">
								<span class="radioItem-num">已选{{checkRightNow.length}}项 ></span>
							</div>
						</div>
						<!-- <van-checkbox
							icon-size="0.4rem"
							name="2"
							shape="square"
							:disabled="checkDisable"
							:value="!!checkRightNow.length"
							@click="()=>checkChang('IMMEDIATELY')">
							<div class="df jfsb aic">
								<div class="abnormal">
								部分检查情况异常，责令立即改正
								</div>
								<van-cell
									style="padding: 5px 0 5px 5px;white-space: nowrap"
									:title="'已选' + checkRightNow.length + '项'"
									is-link @click.stop="gotoList('IMMEDIATELY')"
								></van-cell>
							</div>
						</van-checkbox> -->
						<div class="mt10 ml20 fz12 FontColorInfo">《责令立即改正通知》</div>
					</div>
					<div class="radioItem">
						<div class="radioItem-name" @click="()=>checkChang('DEADLINE')">
							<van-checkbox name="3" :value="!!checkDeadline.length" shape="square">部分检查情况异常，责令限期改正</van-checkbox>
							<div @click.stop="gotoList('DEADLINE')">
								<span class="radioItem-num">已选{{checkDeadline.length}}项 ></span>
							</div>
						</div>
						<!-- <van-checkbox
							icon-size="0.4rem"
							name="3"
							shape="square"
							:disabled="checkDisable"
							:value="!!checkDeadline.length"
							@click="()=>checkChang('DEADLINE')">
							<div class="df jfsb aic">
								<van-cell
									title="部分检查情况异常，责令限期改正"
									:value="`已选${checkDeadline.length}项`"
									is-link @click.stop="gotoList('DEADLINE')"
								></van-cell>
							</div>
						</van-checkbox> -->
						<div class="mt10 ml20 fz12 FontColorInfo">《责令限期改正通知》</div>
					</div>
			</div>

			<div class="btn" >
				<van-button type="info" @click="sure" :disabled="disableSure" >确定</van-button>
			</div>
		</div>
    <!-- 弹出地图展示 -->
    <van-popup
        v-model="showDetailState"
        position="bottom"
        @click-overlay="closeOverLay"
        :style="{ height: '100vh' }">
      <div>
        <div class="headNav">
          <van-nav-bar
              :title="title"
              @click-left="closeOverLay"
              :left-arrow="true"
          >
<!--            <template #right>-->
<!--&lt;!&ndash;              <van-icon v-if="iconName" :name="iconName" size="18" @click="rightIconClick" />&ndash;&gt;-->
<!--            </template>-->
          </van-nav-bar>
        </div>
        <div class="content-check">
          <div class="content">
            <van-checkbox-group
                :value="checkGroupList"
            >
              <div v-for="item in checkResultList" class="df jfsb aic item" style="padding: 10px" :key="item.id">
				  <van-cell :title="item.enforce_class || item.item_name" :label="item.item_content || item.enforce_content">
					  <van-checkbox
						icon-size="0.4rem"
						:name="item.id"
						@click="()=>checkBoxChange(item.id)"
						shape="square"
					></van-checkbox>
				  </van-cell>
                <!-- <div class="df">
                  <span class="color3 mr5">{{item.enforce_content||''}}</span>
                  <span>{{item.enforce_class}}</span>
                </div>
                 -->
              </div>
            </van-checkbox-group>
          </div>
          <van-button type="info" class="submitBtn" @click="closeOverLay">提交</van-button>
        </div>
      </div>

    </van-popup>
		<!-- 遮罩层 -->
		<v-mask :showOverLay="showOverLay" :tipMsg="tipMsg"></v-mask>
	</div>
</template>

<script>
import headNav from "@/components/headNav.vue";
import mask_overLay from "@/components/overLay_xy.vue";
import { get, post, put } from "@/utils/http.js";
import moment from "moment";
import _ from 'lodash';
import { Dialog } from 'vant';
import { dateFormat } from '@/utils/tool';

export default {
	name: "checkResult",
	components: {
		headNav,
		"v-mask": mask_overLay,
	},
	data() {
		return {
      		showDetailState:false,
			showTimeReal: false,
			Judeg: "",
			resultList: "",
			checkCheck: "",
			checkCheckGroup: [],
			checkDisable: false,
			topDisabled: false,
			showOverLay: false,
			tipMsg: "加载中",
			allTime: 0,
			checkContent: "",
			commuteTime: "",
			hasRes: false,
			checkList:[],
			// checkGroupList:[],
			checkType:'',
			title:'',
			checkResultList: [],
			// checkDeadline:false,
			// checkRightNow:false
		};
	},
	mounted() {
		this.init();
	},
  computed:{
    checkGroupList(val){
      return (this.checkList||[]).filter(item=>item.correct_type === this.checkType).map(item=>item.id)
    },
    checkRightNow(val){ // 立刻
      return (this.checkList||[]).filter(item=>item.correct_type === 'IMMEDIATELY')
    },
    checkDeadline(val){ // 限期
      return (this.checkList||[]).filter(item=>item.correct_type === 'DEADLINE')
    },
    disableSure() {
      return !!(this.checkList||[]).find(item=>!item.correct_type)
    },
  },
  // watch:{
	//   checkList()
  // },
	methods: {
    checkBoxChange(itemId){
     let tmpList = this.checkList||[]
      let findItem = tmpList.find(item=>item.id === itemId)
      if(findItem){
        if (findItem.correct_type){
          findItem.correct_type = findItem.correct_type ==='IMMEDIATELY' ?'DEADLINE' :'IMMEDIATELY'
        }else {
          findItem.correct_type = this.checkType
        }
      }
      let noCheckType = this.checkType === 'IMMEDIATELY' ? 'DEADLINE' :'IMMEDIATELY'

      for (let i =0;i<tmpList.length;i++){
        let findItem = tmpList[i]

        if (findItem=== itemId){

          if (findItem.correct_type){
            findItem.correct_type = findItem.correct_type === this.checkType ? noCheckType :this.checkType
          }else {
            findItem.correct_type = this.checkType
          }
        }else {

          findItem.correct_type =findItem.correct_type === this.checkType? this.checkType:noCheckType
        }
      }
     this.checkList = [...tmpList]
    },
	  // 关闭详情
    closeOverLay(){
      this.showDetailState=false
    },
    checkChang(b){
      let tmpList = this.checkList
      let filterItems = tmpList.filter(item=>item.correct_type ===b)
      if (filterItems.length !== 0){
        filterItems.forEach(item=>item.correct_type=null)
      }else {
        tmpList.filter(item=>!item.correct_type).forEach(item=>item.correct_type=b)
      }
      this.checkList=[...tmpList]
    },
	  // 跳转至列表
  	async  gotoList(type){
		  if (this.checkRightNow.length == 0 && this.checkDeadline.length == 0) {
			  this.checkChang(type);
			  return
		  }

		this.checkType=type
		this.showDetailState=true
		if(type==='IMMEDIATELY'){
			this.title='责令立即改正';
			this.checkResultList = this.checkRightNow;
		}else {
			this.title='责令限期改正';
			this.checkResultList = this.checkDeadline;
		}
    },
		// 初始化
		async init() {
			this.tipMsg = "加载中";
			this.showOverLay = true;
      		await this.getPageListApi();
			if (this.$route.params.status === "normal") {
				this.hasRes = true;
			} else {
				this.hasRes = false;
			}
			const judgeTime = this.$store.state.taskInfo.taskInfo.checkTime;

			if (judgeTime !== null) {
				this.hasRes = true;
				this.Judeg = "判断";
			} else {
				this.hasRes = false;
			}

			if (this.resultList.length === 0) {
				this.checkCheck = true;
				this.topDisabled = true;
				this.Judeg = "";
			} else {
				this.topDisabled = true;
			}
			this.showOverLay = false;
		},

		// 获取列表 信息
		async getPageListApi() {
			this.resultList = [];
			await get("/v2/api/enforce-job/item", {
			  page:1,
				size: 999,
				query:`job_id==${this.$route.params.ID};check_result==2`,
			}).then(async(res) => {
				if (res?.data) {
				  for (let i = 0;i<res?.data.length;i++){
				    let item = res.data[i] || {}
						item.index = i + 1;
						if (item.create_time) {
							item['createdTime'] = dateFormat('YYYY-mm-dd HH:MM:SS', new Date(item.create_time));
						}
						// if (item.item_id){
							// let tmpRes = await this.$http.get(`/v2/api/enforce-handbook/${item.item_id}`).catch(()=>null)
							// try {
							// 	let tmpRes = await this.$http.get(`/v2/api/enforce_job_template_handbook/${item.item_id}`).catch(()=>null)
							// 	item['enforce_content'] = tmpRes.data['enforce_content'];
							// 	item['enforce_class'] = tmpRes.data['enforce_class'];
							// } catch (error) {
							// 	continue;
							// }
							// item['createdTime'] = moment(item['create_time']).format('YYYY-MM-DD hh:ss:mm');
						// }
						this.resultList.push(item);
						this.checkList.push(item);
					}
				}
			});
		},

		backPage() {
			this.$router.go(-1);
		},

		turnjudeg() {
			this.$router.push(
				`/checkResultDetail/${this.$route.params.ID}/${this.$route.params.currentID}`
			);
		},

		// 跳转检查详情页面
		gotoDangerDetail(item) {
			console.log('item: ', item);
			this.$router.push({
                name: 'historyItemDetail',
                params: item
            })
			// this.$router.push(`/dangerDetail/${item.item_id}`);
		},

		sure() {
		/*	if (this.checkContent === "") {
				this.$toast.fail("请输入检查时间");
				return;
			} else if (this.commuteTime === "") {
				this.$toast.fail("请输入通勤时间");
				return;
			} else if (this.checkCheckGroup.length === 0 && !this.checkCheck) {
				this.$toast.fail("请选择改正方式");
				return;
			} else {
				let judge = "";

				if (this.checkCheck) judge = 1;
				else judge = this.checkCheckGroup.join(",");

				let submitData = {
					checkJudge: judge.toString(),
					trueCheckContTime: this.checkContent,
					trueCommutingTime: this.commuteTime,
					trueCheckTime: `${this.allTime}h (内容检查 ${this.checkContent}h +  通勤时间 ${this.commuteTime}h)`,
					id: this.$route.params.currentID,
				};*/

			if (this.resultList.length == 0) {
				// this.$router.push(`/correctionNotice/${this.$route.params.ID}`);
				const vm = this;
				Dialog.confirm({
					title: '温馨提示',
					message: '是否归档任务？',
				}).then(() => {
					vm.$http.put(`/v2/api/enforce-job/${vm.$route.params.ID}`, {
						job_status: 'ARCHIVED',
						enforce_result: 'PASS',
        				finish_time: new Date()
					}).then(res => {
						vm.$toast.success('归档成功！');
						vm.$router.back();
					})
				}).catch(e => {

				})
				return;
			}

			this.showOverLay = true;
			this.tipMsg = "提交中";
			put(`/v2/api/enforce-job/${this.$route.params.ID}`, {
				enforce_result: 'NOT_PASS',
			})

			put("/v2/api/enforce-job/item", this.checkList).then((res) => {
				this.showOverLay = false;
				this.$router.replace(`/correctionNotice/${this.$route.params.ID}`);
			/*	if (res.success === true) {
					if (this.checkCheck) {
						this.$router.push(
							`/dailyDetails/${this.$route.params.currentID}`
						);
					} else {
						this.$router.push(
							`/checkResultDetail/${this.$route.params.ID}/${this.$route.params.currentID}`
						);
					}
				} else {
					this.$toast.fail(`${res.msg}`);
				}*/
			}).catch(()=>{
				this.showOverLay = false;

			});
		},

		// 第一个checkBox改变
		firstCheckChange() {
			if (this.checkCheck == true) {
				this.checkDisable = true;
				this.checkCheckGroup = [];
			} else {
				this.checkDisable = false;
			}
		},

		// 限制输入框
		contentInputChange(value) {
			if (isNaN(value) || value.trim() === "") {
				this.checkContent = "";
			}
		},

		contentInputBlur() {
			this.allTime = 0;
			if (this.checkContent) {
				this.checkContent = parseFloat(this.checkContent).toFixed(1);
				if (this.commuteTime === "") {
					this.allTime = 0 + parseFloat(this.checkContent);
				} else {
					this.allTime =
						parseFloat(this.commuteTime) +
						parseFloat(this.checkContent);
				}
			}

			this.allTime = this.allTime.toFixed(1);
		},

		// 限制输入框
		commuteInputChange(value) {
			if (isNaN(value) || value.trim() === "") {
				this.commuteTime = "";
			}
		},

		commuteInputBlur() {
			this.allTime = 0;
			if (this.commuteTime) {
				this.commuteTime = parseFloat(this.commuteTime).toFixed(1);
				if (this.checkContent === "") {
					this.allTime = 0 + parseFloat(this.checkContent);
				} else {
					this.allTime =
						parseFloat(this.commuteTime) +
						parseFloat(this.checkContent);
				}
			}
			this.allTime = this.allTime.toFixed(1);
		},

		sureTimePlan() {
			if (this.checkContent === "" || this.commuteTime === "") {
				this.$toast.fail("检查时间不能为空");
			} else {
				this.showTimeReal = false;
			}
		},
	},
};
</script>

<style lang="scss" scoped>
.checkResult {
  .headNav {
    position: fixed;
    top: 0;
    width: 100%;
    z-index: 99;

    .van-nav-bar__title {
      font-size: 15px;
    }

    .van-nav-bar__right {
      .van-nav-bar__text {
        color: #0066ff;
      }
    }

    .van-nav-bar__left {
      .van-icon.van-icon-arrow-left.van-nav-bar__arrow {
        color: #787878;
      }
    }

    .van-nav-bar__content {
      // border-bottom: 1px solid #b4b4b6;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }

    .van-nav-bar__text {
      font-size: 14px;
    }

    .van-icon {
      font-size: 20px !important;
      color: #0073ac;
    }
  }
  .content-check{
    padding: 50px 10px 10px;
    .item{
      border-bottom: 1px solid #dfdfdf;
    }
    .content{
      height: calc(100vh - 105px);
      overflow-y: auto;
    }
    .submitBtn{
      width: 100%;
    }
  }
  .abnormal{
    white-space: nowrap;  //强制不换行
    text-overflow:ellipsis; //省略号显示
  }
	font-size: 14px;
  .title{
    font-size: 16px;
  }
	.headTip {
		margin-bottom: 10px;
		padding: 0 15px;
	}

	.color1 {
		color: #02a7f0;
	}

	.color2 {
		color: #d9001b;
	}

	.color3 {
		color: #7f7f7f;
	}

	.danger {
		margin-top: 57px;
		padding: 0 10px;
	}

	.noProblem {
		padding: 30px 15px;
		background-color: #fff;
		border-bottom: 1px solid #c7c9cb;
		color: #3fbf83;
		display: flex;
		align-items: center;
		justify-content: center;
		font-weight: bold;
	}
  .colorRed{
    color:red
  }

	.dangerList {
		display: flex;
		background-color: #fff;
		justify-content: space-between;
		border-bottom: 1px solid #c7c9cb;

		.index {
			width: 40px;
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 16px;
			font-weight: bold;
		}

		.dangerContent {
			display: flex;
			flex-direction: column;
			padding: 0px 15px;
			font-size: 12px;
			color: #8f9091;
			padding-left: 0;
		}
	}

	.checkJudge {
		margin-top: 10px;
		padding: 0 10px;

		.radio {
			.radioItem {
				margin: 0px 0;
				padding: 10px 8px;
				background-color: #fff;
				border-bottom: 1px solid #ddd;

				.radioItem-name {
					display: flex;
					align-items: center;
					justify-content: space-between;

					.radioItem-num {
						font-size: 13px;
						color: #5c5c5e;
					}
				}
			}

			.radioItem.itemFirst {
				margin-bottom: 15px;
			}
		}
	}

	.btn {
		margin-top: 30px;
		display: flex;
		justify-content: space-around;

		button {
			flex: 1;
			margin: 0 20px;
		}
	}

	.timeReal {
		background-color: #f5f5f5;
		margin-top: 10px;
		padding: 0 10px;

		.popContent {
			padding: 10px 20px;
			padding-bottom: 0;

			.topInfo {
				display: flex;
				justify-content: center;
				align-items: center;
				padding: 5px 0;
				color: #323233;
			}

			.totalTime {
				display: flex;
				justify-content: center;
				align-items: center;
				font-size: 12px;
				color: #acacac;
				padding: 5px 0;
				margin-left: 5px;
			}

			.inputContent {
			}

			.popBtn {
				display: flex;
				justify-content: space-between;
				margin-top: 10px;
				margin-bottom: 10px;

				div {
					height: 40px;
					text-align: center;
					line-height: 40px;
					margin: 0 5px;
					background-color: #dcdcdc;

					&:last-child {
						background-color: #0066ff;
						color: #ffffff;

						&:active {
							background: #0189ff;
						}
					}

					&:active {
						background: #e8e8e8;
					}
				}
			}
		}
	}
}
</style>

<style lang="scss">
.checkResult {
  height: 100vh;
  overflow: auto;
	.van-cell {
		display: flex;
		align-items: center;
		font-size: 13px;
		color: #5c5c5e;

		&::after {
			border-bottom: 1px solid #888888;
		}
	}

	.dangerList {
		.van-cell.van-cell--clickable {
			padding: 5px 15px 5px 0;
		}
	}

	.van-radio__label {
		color: #767676;
	}

	.van-button.van-button--default.van-button--normal {
		background-color: #d7d7d7;
		color: #fff;
	}

	.van-cell::after {
		border: none;
	}

	.timeReal {
		.van-cell.van-cell--clickable {
			border-bottom: 1px solid #c5c5c5;
		}
	}
}
.content-check {
	.van-cell {
		justify-content: space-between;
		.van-cell__title {
			flex: 20;
		}
	}
}
</style>
