<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px" style="position: relative">
       <el-form-item label="时间" prop="timeRanage">
        <el-date-picker
            v-model="queryParams.timeRanage"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button icon="el-icon-plus" size="mini"    v-hasPermi="['system:report:add']" @click="goAdd">新增</el-button>
        <el-popconfirm
          title="确定要合并所选报备？"
          @confirm="mergeReport"
        >
          <el-button slot="reference" type="primary" icon="el-icon-notebook-2" v-hasPermi="['system:report:sp']"  size="mini" style="margin-left: 10px">合并</el-button>
        </el-popconfirm>
<!--        <el-button icon="el-icon-notebook-2" size="mini" @click="mergeReport">合并</el-button>-->
      </el-form-item>

      <div style="    position: absolute;top: 0;right: 0;">
        <el-button type="primary" icon="el-icon-warning-outline"  v-hasPermi="['system:report:sp']" size="mini" @click="handlect">冲突检测</el-button>
        <el-button type="primary" icon="el-icon-help" size="mini"  v-hasPermi="['system:report:sp']" @click="handlemerge">合并检测</el-button>
      </div>
    </el-form>


    <el-table ref="listtbl" v-loading="loading" :data="reportList" default-expand-all row-key="id" :tree-props="{children: 'children', hasChildren: 'hasChildren'}" @select="tblselect" @selection-change="handleSelectionChange" :row-class-name="tableRowClassName" @row-click="tableclick">
      <el-table-column type="selection" width="40" align="center"   @selectable="selectable"/>
<!--      <el-table-column-->
<!--        type="index"-->
<!--        width="50" fixed="left">-->
<!--      </el-table-column>-->
      <el-table-column label="编号" align="center" prop="id" fixed="left" width='200'>
        <template v-slot:="scope">
          <span>{{scope.row.id}}</span>
        </template>
      </el-table-column>
      <el-table-column label="施工路段" align="center" prop="section" width='200' fixed="left"/>
      <el-table-column label="方向" align="center" prop="direction" width='100'>
      <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_direction" :value="scope.row.direction"/>
        </template>
      </el-table-column>
      <el-table-column label="起止桩号" align="center"  width='300'>
        <template v-slot="scope">
          <div>K{{scope.row.startKm?scope.row.startKm:'0' }}+{{scope.row.startHectometer?scope.row.startHectometer:'0' }} ~ K{{scope.row.endKm?scope.row.endKm:'0' }}+{{scope.row.endHectometer?scope.row.endHectometer:'0' }}</div>
        </template>

      </el-table-column>
<!--      <el-table-column label="开始公里桩" align="center" prop="startKm" width='100'/>-->
<!--      <el-table-column label="开始百米桩" align="center" prop="startHectometer" width='100'/>-->
<!--      <el-table-column label="结束公里桩" align="center" prop="endKm" width='100'/>-->
<!--      <el-table-column label="结束百米桩" align="center" prop="endHectometer" width='100'/>-->
       <el-table-column label="施工内容一" align="center" prop="contentOne" width="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.content_one" :value="scope.row.contentOne"/>
        </template>
      </el-table-column>
       <el-table-column label="施工内容二" align="center" prop="contentTwo" width="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.content_two" :value="scope.row.contentTwo"/>
<!--          <div v-if="scope.row.contentOne != 2">{{scope.row.contentTwo}}</div>-->
        </template>
      </el-table-column>
      <el-table-column label="占用车道" align="center" prop="lane" />
      <el-table-column label="预计开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预计结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="现场负责人" align="center" prop="manageUser" width="120"/>
      <el-table-column label="现场负责人手机号" align="center" prop="managePhone" width="120"/>
      <el-table-column label="现场安全员" align="center" prop="saveUser" width="120"/>
      <el-table-column label="安全员手机号" align="center" prop="savePhone" width="120"/>
      <!-- <el-table-column label="填报人" align="center" prop="createUser" /> -->
      <!-- <el-table-column label="修改人" align="center" prop="updateUser" /> -->
      <!-- <el-table-column label="是否合并 0：否 1：是" align="center" prop="isMerge" /> -->
       <el-table-column label="状态" align="center" prop="status" width="120" fixed="right">
        <template slot-scope="scope">
          <div>
            <div :class="scope.row.status=='1'?'status_wtj':scope.row.status=='2'?'status_dsh':scope.row.status=='3'?'status_ysh':scope.row.status=='4'?'status_yjj':'status_yhb'" style="display: inline-block;vertical-align: middle;margin-right: 5px;width:10px;height: 10px;border-radius: 5px" ></div>
            <dict-tag style="display: inline-block" :options="dict.type.report_status" :value="scope.row.status"/>
          </div>

          <!-- <div v-if="scope.row.report_status != 2">{{scope.row.contentTwo}}</div> -->
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150px" fixed="right">
        <template slot-scope="scope">

          <div v-if="scope.row.isMerge==='-1'">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click.stop="handleDetail(scope.row)"

            >查看</el-button>
            <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="scope.row.status==='1'||scope.row.status==='4'"
            @click.stop="handleUpdate(scope.row)"
            v-hasPermi="['system:report:edit']"
          >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              v-if="scope.row.status==='1'||scope.row.status==='4'"
              @click.stop="handleDelete(scope.row)"
              v-hasPermi="['system:report:remove']"
            >删除</el-button>


              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                v-if="scope.row.status==='2' && scope.row.auditDept+'' === currentuserdeptid+''"
                @click.stop="handleSP(scope.row)"
                v-hasPermi="['system:report:sp']"

              >审批</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              v-if="scope.row.status==='3' "
              @click.stop="handleExport(scope.row)"
              v-hasPermi="['system:report:sp']"

            >导出</el-button>
          </div>



        </template>
      </el-table-column>
    </el-table>

    <pagination
    style="background:none"
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


    <el-dialog title="施工审批"  :visible.sync="spvisible" width="500px" append-to-body>
      <el-form ref="form" :model="spform"  label-width="150px">
        <el-form-item label="审批意见" >
          <el-input v-model="spform.msg" type="textarea" placeholder="请输入审批意见" />
        </el-form-item>


        <el-form-item label="审批结果" >
          <el-radio v-model="spform.status" label="1">同意</el-radio>
          <el-radio v-model="spform.status" label="2">不同意</el-radio>
        </el-form-item>
        <el-form-item label="发送部门" v-if="spform.status=='1' && nexdept" >
          <el-radio  :value="nexdept"   :label="nexdept+''">{{ alldept.filter(i=>{ return i.deptId == nexdept}).length>0?alldept.filter(i=>{ return i.deptId == nexdept})[0].deptName:"" }}</el-radio>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { listReport, getReport, delReport, addReport, updateReport,collisionDetection,mergeQuery,mergeReport } from "@/api/system/report";
import moment from "moment";
import {
  listConfig,
  getConfig,
  delConfig,
  addConfig,
  updateConfig,
  refreshCache,
  getConfigKey
} from "@/api/system/config";
import { listDept, getDept, delDept, addDept, updateDept, listDeptExcludeChild } from "@/api/system/dept";

export default {
  name: "Report",
  dicts: ['sys_direction','content_one','content_two','report_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      spvisible:false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      reportList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        planId: null,
        lane: null,
        startTime: null,
        endTime: null,
        manageUser: null,
        managePhone: null,
        saveUser: null,
        savePhone: null,
        createUser: null,
        updateUser: null,
        isMerge: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // currentuserdeptid:"",
      spform:{
        status:"1",
        reportid:0,
        msg:"",
        ext1:"",
      },
      nexdept:null,
      alldept:[],
      spl:[],
    };
  },
  created() {
    this.getList();
  },
  computed:{
    currentuserdeptid() {
      return this.$store.state.user.dept.deptId;
    }

  },
  mounted() {
    this.$parent.divSelect =2;
    this.$parent.activeIndex='1';

    listDept({}).then(res=>{
      this.alldept = res.data;
    });
    getConfigKey("spflow").then(res=>{
     res = JSON.parse(res.msg);

      this.spl = res;
      for (var index in this.spl) {
        var tempc = this.spl[index];
        var indexc =  tempc.findIndex((i)=>i+"" == this.currentuserdeptid+"");
        // console.log(tempc)
        if(indexc!=-1){

          this.nexdept =  indexc+1 == tempc.length?null:tempc[indexc+1];
          break;
        }
      }
    })





  },
  methods: {
     goAdd(){
         localStorage.setItem("currentreport",JSON.stringify({ routerName:'新增'}));
          this.$router.push({path: '/addReport'})
    },
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      listReport(this.addDateRange(this.queryParams, this.queryParams.timeRanage)).then(response => {
        this.reportList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.spvisible = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        planId: null,
        lane: null,
        startTime: null,
        endTime: null,
        manageUser: null,
        managePhone: null,
        saveUser: null,
        savePhone: null,
        createUser: null,
        createTime: null,
        updateUser: null,
        updateTime: null,
        isMerge: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },


    tblselect(selection, row){
      if(row.isMerge!=='-1'){
        this.$refs.listtbl.toggleRowSelection(row,false);
      }

    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      selection.map(item => {
        if(item.isMerge!=='-1'){


        }
      })




      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length;
    },
    tableRowClassName({row, rowIndex}){
      if(row.cids!=null){
        return row["css"]?row["css"]:"ct1";
      }
      if(row.isMerge!='-1'){
        return "child5";
      }
      return '';

    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加【请填写功能名称】";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      row.routerName = '修改'
      localStorage.setItem("currentreport",JSON.stringify(row));
      this.$router.push({path: '/addReport'})
    },
    handleDetail(row){
      row.routerName = '详情'
      localStorage.setItem("currentreport",JSON.stringify(row));
      this.$router.push({path: '/addReport'})
    },
    /** 提交按钮 */
    submitForm() {
          if (this.spform.reportid != null) {
            var ext1 =  JSON.parse(this.spform.ext1==undefined?"[]":this.spform.ext1) ?? [];
            var timedate =  moment().format("YYYY-MM-DD HH:mm:ss");
            ext1.push({"content": `审批结果：${this.spform.status==="1"?'同意':'不同意'} 意见：${this.spform.msg}`, "deptname": this.$store.state.user.dept.deptName, "timestamp": timedate})
            ext1 = JSON.stringify(ext1);
            updateReport({id:this.spform.reportid,ext1:ext1}).then((response) => {
              this.$modal.msgSuccess("成功");
              this.$router.push({ path: "/report" });
              this.handleQuery();
            });


          }
          this.spvisible = false;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除编号为"' + ids + '"的数据项？').then(function() {
        return delReport(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    tableclick(row, column, event){
      if(row.isMerge!=-1){
        return;
      }
      row.routerName = '详情'
      localStorage.setItem("currentreport",JSON.stringify(row));
      this.$router.push({path: '/addReport'})
    },

    handleSP(row){
      this.spvisible = true;
      this.spform.reportid = row.id;
      this.spform.ext1 = row.ext1;
    },


    /** 导出按钮操作 */
    handleExport(row) {
      this.download('system/report/export', {
        id:row.id
      }, `report_${new Date().getTime()}.docx`)
    },
    selectable(row, index){
      return (row.isMerge+"") === "-1";

    },
    handlemerge(){
      const  ids = this.ids;
      if(ids.length>0){
        mergeQuery(ids).then(res=>{
          var msg = "<span>有施工报备可以合并！</span><br/> ";
          var mapc = {};
          var hasc = false;
          for (const index in this.reportList) {
            var c = this.reportList[index];
            mapc[c.id] = c;
            var p= res.data.find(item=>{return item.id+"" === c.id+"" });
            if(p && p.cids){
              c.cids = p.cids;
              c["css"] = 'ct5';
              hasc = true;
            }
          }
          for(const index in this.reportList){
            var c = this.reportList[index];
            if(c.cids  ){
              msg+=`施工报备单编号${c.id} 与 ${c.cids.split(",").map(i=>'施工报备单编号'+i).join("或")} 可以合并 <br/>`;
            }
          }
          msg+="<span style='color:#ffba00'>原因：施工结束时间相隔不超过1小时（包含1小时）、同方向、同车道（都在同一车道，或者1、2车道；3、4（应急车道）车道则为同车道），同桩号（指有包含关系或相同且修的全长在2.5公里范围内）判断为合并。</span>";
          if(hasc) {
            this.$confirm(msg, '提示', {
              confirmButtonText: '确定',
              type: 'warning',
              showCancelButton: false,
              dangerouslyUseHTMLString: true
            }).then(() => {

            }).catch(() => {

            });
          }else{
            this.$confirm('未检测到可以合并的报备', '提示', {
              confirmButtonText: '确定',
              type: 'info',
              showCancelButton: false,
              dangerouslyUseHTMLString: true
            }).then(() => {

            }).catch(() => {

            });
          }


          // this.$refs.listtbl.doLayout();

        })
      }else{
        this.$modal.msgWarning("未选择施工报备");
      }

    },

    mergeReport(){
      const  ids = this.ids;
      if(ids.length>1){
        mergeReport(ids).then(res=>{
          //获取合集id
           var sysreport = res.data["p"];
           if(sysreport){
             var listc = res.data["childlist"];
             sysreport.dept= listc.map(i=>i.dept).join(",");
             sysreport.planId= listc[0].planId;
             sysreport.direction= listc[0].direction;
             sysreport.section= listc[0].section;
             sysreport.contentOne= '5';
             sysreport.contentTwo= '9';
             sysreport.lane= listc.map(i=>i.lane).join(",").split(",").filter(function(value,index,self){
               return self.indexOf(value) === index;
             }).join(",");
             sysreport.manageUser= listc.map(i=>i.manageUser).join(",");
             sysreport.managePhone= listc.map(i=>i.managePhone).join(",");
             sysreport.saveUser= listc.map(i=>i.saveUser).join(",");
             sysreport.savePhone= listc.map(i=>i.savePhone).join(",");
             sysreport.status = '2';
             sysreport.createBy = 'sys';
             sysreport.startKm = listc.sort((a, b) => parseInt(b.startKm) - parseInt(a.startKm)).slice().pop().startKm;
             sysreport.startHectometer = listc.sort((a, b) => parseInt(b.startKm) - parseInt(a.startKm)).slice().pop().startHectometer;
             sysreport.endKm = listc.sort((a, b) => parseInt(a.endKm) - parseInt(b.endKm)).slice().pop().endKm;
             sysreport.endHectometer = listc.sort((a, b) => parseInt(a.endKm) - parseInt(b.endKm)).slice().pop().endHectometer;
             sysreport.startTime = listc.sort((a, b) => moment(b.startTime).unix() - moment(a.startTime).unix()).slice().pop().startTime;
             sysreport.endTime = listc.sort((a, b) => moment(a.endTime).unix() - moment(b.endTime).unix()).slice().pop().endTime;


             sysreport.contentDes =  listc.map((i,index)=>{
               var section = i.section;
               var cone = this.dict.type.content_one.filter(p=>{ return p.value==i.contentOne}).map(p=>p.label).join("");
               var ctwo = this.dict.type.content_two.filter(p=>{ return p.value==i.contentTwo}).map(p=>p.label).join("");
               var time = i.startTime + '~' + i.endTime;
               var lan = i.lane;
               var addr = `K${i.startKm?i.startKm:"0" }+${i.startHectometer?i.startHectometer:"0" } ~ K${i.endKm?i.endKm:"0" }+${i.endHectometer?i.endHectometer:"0"}`;
               return `${index+1}、${section}${addr}${cone}${ctwo}${i.contentDes ?? ""} 占用第${lan}车道(${time}) \r\n 负责人：${i.manageUser + "  "+i.managePhone} \r\n 安全员：${i.saveUser + "  "+i.savePhone}`  }).join("\r\n\r\n");
             updateReport(sysreport).then(res=>{
               this.handleQuery();
             })



           }else{
             this.$modal.msgWarning("合并错误！");
           }

        });

      }else{
        this.$modal.msgWarning("请选择2条以上的施工报备");
      }

    },
    handlect(){
      const  ids = this.ids;
      if(ids.length>0){
        collisionDetection(ids).then(res=>{
          var msg = "<span>有施工报备存在冲突！</span><br/> ";
          var mapc = {};
          var hasc = false;
          for (const index in this.reportList) {
            var c = this.reportList[index];
            mapc[c.id] = c;
            var p= res.data.find(item=>{return item.id+"" === c.id+"" });
            if(p && p.cids){
              c.cids = p.cids;
              c["css"] = 'ct1';
              hasc = true;
            }
          }
          for(const index in this.reportList){
            var c = this.reportList[index];
            if(c.cids  ){
              msg+=`施工报备单编号${c.id} 与 ${c.cids.split(",").map(i=>'施工报备单编号'+i).join("、")} 冲突 <br/>`;
            }
          }
          msg+="<span style='color:#ffba00'>原因：同时间指时间重合超过1小时（不包含1小时）、同方向、间距小于5公里（不包含5公里）。</span>";
          if(hasc) {
            this.$confirm(msg, '提示', {
              confirmButtonText: '确定',
              type: 'warning',
              showCancelButton: false,
              dangerouslyUseHTMLString: true
            }).then(() => {

            }).catch(() => {

            });
          }else{
            this.$confirm('未检测到冲突', '提示', {
              confirmButtonText: '确定',
              type: 'info',
              showCancelButton: false,
              dangerouslyUseHTMLString: true
            }).then(() => {

            }).catch(() => {

            });
          }


          // this.$refs.listtbl.doLayout();

        })
      }else{
        this.$modal.msgWarning("未选择施工报备");
      }

    }
  }
};
</script>

<style>
.ct1{
  background: #fce8e8 !important;
}
.ct2{
  background: #77FFB7 !important;
}
.ct3{
  background: #FFFD77ED !important;
}
.ct4{
  background: #c5c5fd !important;
}

.ct5{
  background: #c5e8fd !important;
}


.child5{
  background: #efefef !important;
}

.el-table [class*=el-table__row--level] .el-table__expand-icon{
  margin-left:-100px;
  width: 94px;
  font-size: 20px;
}

.el-table-column--selection .cell{
  text-overflow:unset
}
.small-padding .cell{
  padding-left: 0;
  padding-right: 0;
}


.status_dsh{
  background: #1c84c6;
}
.status_wtj{
  background:#f8ac59;
}
.status_ysh{
  background: #13ce66;
}
.status_yjj{
  background: #C03639;
}
.status_yhb{
  background: #99a9bf;
}



</style>

