<template>


    <el-form class="border">
      <el-row :gutter="20">
        <el-col :span="10">
          <el-divider content-position="left" style="font-size: 18px; font-weight: bolder">
            基本信息
          </el-divider>
          <el-form :inline="true" :model="formdata" class="forms" :disabled="viewDetails" label-width="120px">
            <el-form-item label="普测负责单位:">
              <el-input v-model="formdata.orgName" disabled></el-input>
            </el-form-item>
            <el-form-item label="计划开始时间:">
              <el-date-picker
                  v-model.trim="formdata.planStartTime"
                  type="date"
                  placeholder="选择计划开始时间"
                  value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="计划结束时间:">
              <el-date-picker
                  v-model.trim="formdata.planEndTime"
                  type="date"
                  placeholder="选择计划结束时间"
                  value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="普测计划编号:">
              <el-input
                  :disabled="title == '普测计划修改'"
                  v-model="formdata.planNo"
                  placeholder="请输入普测计划编号"
              ></el-input>
            </el-form-item>
            <el-form-item label="计划名称:">
              <el-input v-model="formdata.planName" placeholder="请输入计划名称"></el-input>
            </el-form-item>
            <el-form-item label="测试负责人:">
              <el-input v-model="formdata.leader" placeholder="请输入测试负责人"></el-input>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="14">
          <el-divider content-position="left" style="font-size: 18px; font-weight: bolder">
            添加电站
          </el-divider>
          <div class="mb10" style="display: flex" v-if="!viewDetails">
            <el-input
                v-model="input"
                placeholder="请输入电站数"
                style="width: 240px"
                @input="handleEdit"
                class="mr10"
            ></el-input>
            <el-button
                type="primary"
                :disabled="!input.length > 0"
                icon="el-icon-circle-check"
                size="small"
                @click="Tick"
            >
              按配置勾选
            </el-button>
          </div>
          <el-tree
              :data="treeData"
              show-checkbox
              node-key="id"
              style="overflow-y: auto; height: 490px"
              default-expand-all
              :props="defaultProps"
              :check-strictly="true"
              ref="tree"
          ></el-tree>
        </el-col>
      </el-row>
      <el-divider v-if="title == '计划详情' && formdata.status == 2 && formdata.status == 3" content-position="left"
                  style="font-size: 18px; font-weight: bolder">
        审核意见
      </el-divider>
      <el-input v-if="title == '计划详情' && formdata.status == 2 && formdata.status == 3" disabled type="textarea"
                :rows="2" v-model="textarea">
      </el-input>
      <div slot="footer" style="display: flex; justify-content: center" v-if="!viewDetails"></div>

    </el-form>
</template>

<script>
import Area from '@/views/components/Area/Area.vue'
import Timeinterval from '@/views/components/Timeinterval.vue'
import {dicData} from '@/assets/commjs/dictypeData'
import {
  queryPlan,
  exportSurveyPlan,
  getGeneratrixByCondition,
  getstatationStatList,
  addPlan,
  initDetpStataionTree,
  querySubStatation,
  planStatus,
  getAuditUser, submitAuditUser, MultipartFile, queryPlanResult, surveyResultDownload, delPlan
} from '@/api/Process-supervision/tiaoHarmonicmanagement/harmonicmanagement'

export default {
  name: "normalPlanInit",
  components: {Area, Timeinterval},
  data() {
    return {
      input: '',
      title: '',
      height: null,
      isLoading: false,
      isLoading1: false,
      isLoading2: false,
      isLoading3: false,
      viewDetails: false,
      planAddition: false,
      failed: false,
      universalBus: false,

      chooseAudit: false,
      dialogVisible: false,
      downLoad: false,

      item: ['', ''],
      Downloaddata: [],

      textarea: '',
      // 查询数据
      ruleForm: {
        currentPage: 1,
        pageSize: 20,
        status: '',
        planStartTime: '',
        planEndTime: '',
        orgNo: ''
      },
      form: {
        deptId: '',
        powerStationId: '',
        powerStationName: '',
        powerStationVoltageLevel: ''
      },
      headers: {
        Authorization: window.sessionStorage.getItem('cntoken')
      },
      formdata: {
        orgName: '',
        orgNo: '',
        planStartTime: '',
        planEndTime: '',
        planNo: '',
        planName: '',
        leader: '',
        rgeneralSurveyPlanDetailAddParm: [],
        subCount: '',
        busCount: ''
      },
      temp: {
        id: void 0,
        fileName: '',
        fileType: void 0
      },

      //计划状态
      planstatus: [
        {
          id: 0,
          value: '选项1',
          label: '新建'
        },
        {
          id: 1,
          value: '选项1',
          label: '待审核'
        },
        {
          id: 3,
          value: '选项1',
          label: '审核未通过'
        },
        {
          id: 4,
          value: '选项1',
          label: '已发布'
        },
        {
          id: 5,
          value: '选项1',
          label: '已完成'
        }
      ],
      //所属单位
      companyData: [],
      //变电站/换流站电压等级
      voltageLevelData: [],
      //变电站/换流站名称
      statationName: [],
      exportData: [],
      rightData: [],
      planmanagementData: [],
      detailData: [],
      universalBusData1: [],
      universalBusData2: [],
      multipleSelection: [],
      multipleSelection1: [],
      multipleSelection2: [],
      device: '',
      treeData: [],
      auditUserList: [],
      auditUser: '',
      planNo: [],
      fileList: [],
      formLoading: false,
      defaultProps: {
        children: 'children',
        label: 'name',
        disabled: 'disabled'
      },
      timeOptions: [
        {label: '年份', value: 1},
        {label: '季度', value: 2},
        {label: '月份', value: 3}
        // { label: "周", value: 4 },
        // // { label: "自定义", value: 5 },
      ]
    }
  },
  created() {

  },
  mounted() {
    this.ruleForm.orgNo = JSON.parse(window.sessionStorage.getItem('Info')).deptId
    this.form.deptId = JSON.parse(window.sessionStorage.getItem('Info')).deptId


  },
  methods: {
    //确认发起审核
    auditSubmit() {
      if (!this.auditUser || this.auditUser === '') {
        this.$message({
          message: '请选择审核人!',
          type: 'warning'
        })
        return false;
      }

      let data = {planIds: this.planNo, auditUser: this.auditUser}
      submitAuditUser(data).then(res => {
        if (res && res.code == 'A0000') {
          this.$message({
            message: '提交成功!',
            type: 'success'
          })
          this.chooseAudit = false
          this.initPage()
        }
      })
    },

    //获取审核人列表
    getAuditUser() {
      let param = {roleType: 1}
      getAuditUser(param).then(res => {
        if (res && res.code === 'A0000') {
          this.auditUserList = res.data
        }
      })
    },


    // 合计禁止点击
    selectable(row, index) {
      // 地址不是 "秦皇岛市海港区居民" 才能被选中
      if (!row.selectable) {
        return true
      }
      // 函数必须有返回值且是布尔值
      // 页面刷新后该函数会执行 N 次进行判断(N 为表格行数)
      // 如果没有返回值则默认返回false(全部无法选中)
    },

    //获取类型
    getclassificationData() {
      //电压等级
      this.voltageLevelData = dicData('Dev_Voltage', [])
    },
    //获取数据
    // getData(){
    //   //变电站名称
    //   getstatationStatList().then(res=>{
    //     // console.log(res);
    //     this.statationName=res.data
    //   });
    // },
    changeFn(val) {
      // console.log(val);
      this.statationName.forEach(item => {
        if (item.powerId == val) {
          this.form.powerStationName = item.powerName
        }
      })
    },
    // 在 Input 值改变时触发
    handleEdit(e) {
      let value = e.replace(/^(0+)|[^\d]+/g, '') // 以0开头或者输入非数字，会被替换成空
      value = value.replace(/(\d{15})\d*/, '$1') // 最多保留15位整数
      this.input = value
    },
    // 提交审核
    planReviewFn() {

      if (this.multipleSelection.length === 0) {
        this.$message({
          message: '请选择至少一条计划提交审核',
          type: 'warning'
        })
        return false;
      }

      //需要保证当前用户只能操作自己建的计划


      this.planNo = []
      let flag = true
      let flagFile = true
      this.multipleSelection.forEach(item => {
        if (item.status == 0 || item.status == 2) {
          this.planNo.push(item.planNo)
        } else {
          flag = false
        }

        if (item.isFileUpload !== 1) {
          flagFile = false
        }
      })

      if (!flagFile) {
        this.$message({
          message: '请选择已经上传普测报告的计划进行提交',
          type: 'warning'
        })
        return false;
      }

      if (flag && flagFile) {
        this.chooseAudit = true;

      } else {
        this.$message({
          message: '请选择新建、未通过的计划进行审核！',
          type: 'warning'
        })
      }
    },
    //查询
    initPage() {
      this.isLoading = true
      queryPlan(this.ruleForm).then(res => {
        this.isLoading = false
        this.planmanagementData = res.data.records
      })
    },
    // 递归函数，给每层树赋值disabled
    /*  setDisabled(treeData) {
        treeData.forEach(item => {
          if (item.id !== this.sendMailAccountList.sender) {
            this.$set(item, 'disabled', true)
            if (item.children) {
              this.setDisabled(item.children)
            }
          }
        })
      },*/

    //查看详情
    viewDetailsFn(row) {
      initDetpStataionTree({
        orgId: JSON.parse(window.sessionStorage.getItem('Info')).deptId
      }).then(res => {
        this.treeData = res.data
      })
      this.defaultProps = {
        children: 'children',
        label: 'name'
        // disabled: 'flag'
      }
      this.title = '计划详情'
      this.textarea = row.checkComment
      this.formdata = row
      setTimeout(() => {
        this.$refs.tree.setCheckedKeys(row.subIds)
      }, 0)
      this.planAddition = true
      this.viewDetails = true
    },

    //删除计划
    deletePlan(row) {
      this.$confirm('是否确认删除计划?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        let arr = [row.planNo]
        delPlan(arr).then(res => {
          if (res.code == 'A0000') {
            this.$message({
              message: '删除成功!',
              type: 'success'
            })
            this.initPage()
          }
        })
      })
    },


    //计划新增
    planAdditionFn() {
      initDetpStataionTree({
        orgId: JSON.parse(window.sessionStorage.getItem('Info')).deptId
      }).then(res => {
        this.treeData = res.data
      })
      this.defaultProps = {
        children: 'children',
        label: 'name',
        disabled: 'disabled'
      }
      this.title = '普测计划新增'
      this.planAddition = true
      this.formdata = {
        orgName: JSON.parse(window.sessionStorage.getItem('Info')).deptName,
        orgNo: JSON.parse(window.sessionStorage.getItem('Info')).deptId,
        planStartTime: '',
        planEndTime: '',
        planNo: '',
        planName: '',
        leader: '',
        rgeneralSurveyPlanDetailAddParm: [],
        substation: '',
        Bus: ''
      }
      setTimeout(() => {
        this.$refs.tree.setCheckedKeys([])
      }, 0)
      // this.isLoading2 = true;
      // getDetailData().then((res)=>{
      //     this.isLoading2 = false;
      //     this.formdata.rgeneralSurveyPlanDetailAddParm = res.data
      // })
    },
    //普测计划提交
    submitFn() {

      this.formdata.subIds = this.$refs.tree.getCheckedKeys()
      addPlan(this.formdata).then(res => {
        if (res.code == 'A0000') {
          if (this.title == '普测计划新增') {
            this.$message({
              message: '新增成功!',
              type: 'success'
            })
          } else {
            this.$message({
              message: '修改成功!',
              type: 'success'
            })
          }
          this.planAddition = false
          this.initPage()
        }
      })
    },
    //普测计划保存
    // preservationFn(){
    //   this.planAddition=false;
    // },
    //普测计划取消
    cancelFn() {
      this.planAddition = false
      this.viewDetails = false
    },
    //添加普测母线
    universalBusFn() {
      this.form = {
        deptId: JSON.parse(window.sessionStorage.getItem('Info')).deptId,
        powerStationId: '',
        powerStationName: '',
        powerStationVoltageLevel: ''
      }
      this.universalBus = true
      this.AddQuery()
    },
    //添加查询
    AddQuery() {
      this.isLoading3 = true
      getGeneratrixByCondition(this.form).then(res => {
        this.isLoading3 = false
        this.universalBusData1 = res.data
        this.universalBusData2 = this.formdata.rgeneralSurveyPlanDetailAddParm
        this.universalBusData2.forEach(item => {
          this.universalBusData1.forEach((data, index) => {
            if (data.busbarId == item.busbarId) {
              this.universalBusData1.splice(index, 1)
            }
          })
        })
      })
    },
    // 数据过滤
    formFilter(row, column) {
      if (column.property == 'voltageLevel') {
        let title = ''
        this.voltageLevelData.forEach(item => {
          if (item.value == row.voltageLevel) {
            title = item.label
          }
        })
        return title
      } else {
        return row[column.property]
      }
    },
    //将左边表格选中的数据添加到右边表格
    addDataFn() {
      this.multipleSelection1.forEach(item => {
        // debugger
        this.universalBusData2.push(item)
        this.universalBusData1.forEach((data, index) => {
          if (data.busbarId == item.busbarId) {
            this.universalBusData1.splice(index, 1)
          }
        })
      })
    },
    //删除右侧表哥选中的数据
    deleteData() {
      this.multipleSelection2.forEach(item => {
        this.universalBusData1.push(item)
        this.universalBusData2.forEach((data, index) => {
          if (data.busbarId == item.busbarId) {
            this.universalBusData2.splice(index, 1)
          }
        })
      })
    },
    //清空数据
    emptyFn() {
      this.universalBusData2.forEach(item => {
        this.universalBusData1.push(item)
      })
      this.universalBusData2 = []
    },
    //添加普测母线确认
    determineFn() {
      this.universalBus = false
      this.formdata.rgeneralSurveyPlanDetailAddParm = this.universalBusData2
      // console.log(this.formdata.rgeneralSurveyPlanDetailAddParm);
      let substation = []
      let bus = []
      this.formdata.rgeneralSurveyPlanDetailAddParm.forEach(item => {
        substation.push(item.subId)
        bus.push(item.busbarId)
      })
      substation = [...new Set(substation)]
      bus = [...new Set(bus)]
      this.formdata.subCount = substation.length
      this.formdata.busCount = bus.length
    },
    //添加普测母线取消
    cancel() {
      this.universalBus = false
    },
    //编辑
    editFn(row) {
      this.input = ''
      initDetpStataionTree({
        orgId: JSON.parse(window.sessionStorage.getItem('Info')).deptId
      }).then(res => {
        this.treeData = res.data
      })
      this.defaultProps = {
        children: 'children',
        label: 'name',
        disabled: 'disabled'
      }
      this.title = '普测计划修改'
      this.planAddition = true

      this.formdata = JSON.parse(JSON.stringify(row))
      setTimeout(() => {
        this.$refs.tree.setCheckedKeys(row.subIds)
      }, 0)
    },
    //导出
    exportFn() {
      if (this.multipleSelection.length != 0) {
        exportSurveyPlan(this.exportData).then(res => {
          let blob = new Blob([res], {
            type: 'application/vnd.ms-excel'
          })
          const url = window.URL.createObjectURL(blob)
          const link = document.createElement('a') // 创建a标签
          link.href = url // link.download = "电压暂降事件分析报告"; // 设置下载的文件名
          link.download = '普测计划信息.xls' // 设置下载的文件名
          document.body.appendChild(link)
          link.click() //执行下载
          document.body.removeChild(link)
        })
      } else {
        this.$message({
          message: '请选择数据',
          type: 'warning'
        })
      }
    },


    //导出
    exportExportFn() {
      if (this.multipleSelection.length == 0 || this.multipleSelection.length > 1) {
        this.$message({
          showClose: true,
          message: '请选择1条数据!!!',
          type: 'warning'
        })
        return
      } else {
        this.downLoad = true
        this.isLoading1 = true
        let form = {
          planNo: this.planNo
        }
        surveyResultDownload(form).then(res => {

          this.isLoading1 = false
          this.Downloaddata = res.data

        })
      }
    },


    //计划文件上传
    uploadFn() {
      if (this.multipleSelection.length == 0 || this.multipleSelection.length > 1) {
        this.$message({
          showClose: true,
          message: '请选择1条数据!!!',
          type: 'warning'
        })
        return
      }


      if (this.multipleSelection[0].status !== 0) {
        this.$message.warning("当前状态不支持上传普测报告");
        return false
      }


      this.planNo.push(this.multipleSelection[0].planNo)

      this.dialogVisible = true
      this.fileList = []


    },
    handleChange(file, fileList) {
      this.fileList = fileList
    },
    submitUpload() {
      const formData = new FormData()
      formData.append('planId', this.planNo[0])
      this.fileList.forEach(item => {
        formData.append('file', item.raw)
        // console.log(item.raw, item)
      })


      MultipartFile(formData) //后端上传接口
          .then(res => {
            //  console.log(res);
            // this.$emit('added')
            this.dialogVisible = false
            this.initPage()
          })
          .catch(err => {
            /// console.log(err);
          })
    },
    //查询
    onsubmit() {
      this.isLoading = true

      queryPlanResult(this.ruleForm).then(res => {
        this.isLoading = false
        this.resultsmanagementData = res.data.records
      })
    },

    // 按配置勾选
    Tick() {
      querySubStatation({
        statetionNum: this.input
      }).then(res => {
        this.$refs.tree.setCheckedKeys(res.data.subIds)
      })
    },
    //勾选
    handleSelectionChange(val) {
      this.multipleSelection = val
      this.multipleSelection.forEach(item => {
        this.exportData.push(item.planNo)
      })
    },
    handleSelectionChange1(val) {
      this.multipleSelection1 = val
      //console.log(this.multipleSelection1, this.universalBusData1);
    },
    handleSelectionChange2(val) {
      this.multipleSelection2 = val
      // console.log(this.multipleSelection2, this.universalBusData2);
    },
    // 切换选项
    handleNodeClick(data) {
      // console.log(data);
      this.ruleForm.orgNo = data.id
    },
    handleNodeClick1(data) {
      // console.log(data);
      // if (data.code != null) {
      let form = {
        deptId: data.id
      }
      // 变电站名称
      getstatationStatList(form).then(res => {
        this.statationName = res.data
      })
      // }
      this.form.deptId = data.id
    },
    //每页条数改变时触发 选择一页显示多少行
    handleSizeChange(val) {
      this.ruleForm.pageSize = val
      this.initPage()
    },
    //当前页改变时触发 跳转其他页
    handleCurrentChange(val) {
      this.ruleForm.currentPage = val
      this.initPage()
    },
    //序号
    rowClassName({row, rowIndex}) {
      // console.log(row,rowIndex);
      if (row.voltageLevel == '') {
        row.number = '合计'
      } else {
        row.number = rowIndex + 1
      }
    },
    //重置
    resetFn() {
      this.status = ''
      this.$refs.area.form.valueTitle = JSON.parse(window.sessionStorage.getItem('Info')).deptName
      this.$refs.interval.intervald = 3
      this.$refs.interval.nowTime()
    }
  }
}
</script>

<style scoped>

.border {
  padding: 10px;
  margin: 10px;
  border: 1px solid black;
}

.border-title {
  width: 100px;
  height: 20px;
  margin-top: -20px;
  margin-left: 10px;
  text-align: center;
  background: white;
}

.element-uithree .el-tree{
  overflow: auto;
}
</style>
