<template>
  <div class="gdPlan-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="70px">
        <el-form-item label="委托单位" prop="weituoClient">
          <el-select v-model="queryParams.weituoClient" clearable filterable placeholder="请选择委托单位" @change="getWeituoClientOptions">
            <el-option
              v-for="item in weituoClientOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="委托编号" prop="weituoNo">
          <el-select v-model="queryParams.weituoNo" clearable filterable placeholder="请选择委托编号" @change="getWeituoNoOptions">
            <el-option
              v-for="item in weituoNoOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="getHjlist">搜索</el-button>
        </el-form-item>
      </el-form>
    <uGantt :configColumns="configColumns" :taskLists="taskLists" ref="uGantt" @dbclick="rowDblclick" :uStyle="uStyle" hasReality @cellClick="cellClick">
      <!-- 其他需要自定义的弹窗数据 -->
      <!-- 双击事件弹窗 -->
      <el-dialog :title="title" :visible.sync="dialogVisible" width="45%">
        <el-form ref="currentDbEdit" :model="currentDbEdit" :rules="rules" label-width="80px">
          <el-form-item label="开始时间" prop="start_date">
            <el-date-picker v-model="currentDbEdit.start_date" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" @change="dataChange"></el-date-picker>
          </el-form-item>
          <el-form-item label="持续时间" prop="lastTime">
            <el-input-number v-model="currentDbEdit.lastTime" @change="handleChange" :min="1"></el-input-number>
            <span style="padding-left: 10px;">{{currentDbEdit.end_date}}</span>
          </el-form-item>
          <!-- <el-form-item label="报告编号" prop="reportNo">
            <el-input v-model="currentDbEdit.reportNo" placeholder="请输入报告编号"></el-input>
          </el-form-item> -->
          <el-form-item label="项目经理" prop="pm">
            <el-select v-model="currentDbEdit.pm" placeholder="请选择项目经理" style="width: 100%;">
              <el-option
                v-for="item in manager"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="试验设备" prop="shebeiIdArray">
            <div class="eq-rili-view" style="display: flex;">
              <el-select v-model="currentDbEdit.shebeiIdArray" placeholder="请选择试验设备" style="width: 100%;" multiple>
                <el-option
                  v-for="item in deviceOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
              <div class="search-btn" @click="handleEqCalendar">{{openRl == 1 ? '收起': '展开'}}</div>
            </div>
          </el-form-item>
          <el-calendar v-if="openRl == 1">
            <template slot="dateCell" slot-scope="{date, data}">
              <!-- <div> -->
                <!-- 如果是当前选择月 -->
                <template v-if="data.type === 'current-month'">
                  <!-- 这里加了周六周天的判断 -->
                  <div :class="(date.getDay()==6 || date.getDay()==0)?'weeked' :'notweeked'">{{data.day.substring(8,10)}}</div>
                  <!-- <div :class="(date.getDay()==6 || date.getDay()==0)?'weeked' :'notweeked'">{{data.day.split('-').slice(2).join('-')}}</div> -->
                  <!-- 方法二：在方法中判断设置返回 -->
                  <template v-if="dealMyDate(data.day)">
                    <div v-for="(item, index) in dealMyDate(data.day)" :key="index" class="eqCalendar-item">
                      <!-- <el-tag type="danger" :key="index" style="margin-right: 2px;" @click="chooseDevice(item)">
                        {{ item.deviceName }}
                      </el-tag> -->
                      <div>
                        {{ item.deviceName }}
                      </div>
                    </div>
                  </template>
                  <!-- <el-tag type="danger" v-if="dealMyDate(data.day).length > 0">
                    {{ dealMyDate(data.day)[0].deviceName }}
                  </el-tag> -->
                </template>
                <!-- 不是 -->
                <template v-else>
                  <div style="text-align: right;">{{ data.day.split('-').slice(1).join('-') }}</div>
                </template>
              <!-- </div> -->
            </template>
          </el-calendar>
          <el-form-item label="传感器" prop="chuanganqiArray">
            <el-select v-model="currentDbEdit.chuanganqiArray" multiple filterable placeholder="请选择传感器" style="width: 100%;">
              <el-option
                v-for="item in chuanganqi"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="结束" prop="end_date">
            <el-date-picker v-model="currentDbEdit.end_date" type="date" value-format="yyyy-MM-dd" placeholder="选择日期"></el-date-picker>
          </el-form-item> -->
        </el-form>
        <!-- <div> -->
          <!-- 参数设定是固定格式，千万别改 -->
          <!-- 开始：<el-date-picker v-model="currentDbEdit.start_date" type="date" value-format="yyyy-MM-dd" placeholder="选择日期"></el-date-picker>
        </div>
        <div>
          结束：<el-date-picker v-model="currentDbEdit.end_date" type="date" value-format="yyyy-MM-dd" placeholder="选择日期"></el-date-picker>
        </div> -->
        <!-- 其他需要自定义的弹窗数据 -->
        <!-- <slot/> -->
        <span slot="footer" class="dialog-footer">
          <!-- <el-button @click="remove">删 除</el-button> -->
          <el-button @click="cancel">关 闭</el-button>
          <el-button type="primary" @click="submit" v-if="status == 0">确 定</el-button>
        </span>
      </el-dialog>
    </uGantt>
  </div>
</template>

<script>
import uGantt from '@/components/module-iTDM/uGantt/index.vue'
import {getWeituoClientList, getWeituoInfoListByClient, getDeviceList, getJhList, getManagerList, getCgqList, saveProject, ajaxGetDictItems, saveProjectJl, delProjectJl, getDeviceCalendar} from '@/api/api'
export default {
  name: '',
  components: { uGantt },
  data () {
    return {
      // realityBgIncomplete:实际进行中的进度条颜色，realityBgCompleted：实际已完成的进度条颜色
      uStyle: {
        ganttHeight: 40,planHeight: 26,planBg:'#44c2e5',realityHeight: 1,realityBgIncomplete:'#FFC886',realityBgCompleted:'#B1D5AC',top: 2,
      },
      // width：每列宽度--现在逻辑全部默认显示左边table，右边滚动
      // fixed：现在没有，如果需要一部分固定，一部分滚动，则需要重新设置一下组件
      // resize：暂时没用
      // align：每列文字显示
      // tree：暂时没用
      // 注意：start_date（开始日期）和end_date（结束日期）和add（添加按钮）是固定死的参数名，不能更改
      configColumns: [
        { name: "weituoNo", label: "委托编号", width: 140, fixed: true, resize: true, align: "center", tree: true },
        { name: "testItems", label: "检测项目", width: 80, fixed: true, resize: true, align: "center"},
        { name: "sampleName", label: "样品名称", width: 80, fixed: true, resize: true, align: "center" },
        { name: "sampleModelSpecification", label: "规格型号", width: 80, fixed: true, resize: true, align: "center" },
        { name: "start_date", label: "开始时间", width: 100, fixed: true, resize: true, align: "center" },
        { name: "end_date", label: "结束时间", width: 100, fixed: true, resize: true, align: "center" },
        { name: "statusC", label: "状态", width: 60, fixed: true, resize: true, align: "center" },
        // { name: "add", label:"", width: 30 }
      ],
      // 注意：start_date（开始日期）和end_date（结束日期）和add（添加按钮）是固定死的参数名，不能更改
      // 注意：id和pid也是固定死的参数名，如果需要可以改组件
      // id、task_text: 也是固定死的，如果需要可以改组件
      taskLists: [],
      // taskLists: [{
      //     id: 0,
      //     testItems: 'ceshi',
      //     sampleName: 'ceshi',
      //     start_date: '2023-07-03',
      //     end_date: '2023-07-04',
      //     statusC: '0',
      //     task_text: '111'
      //   }, {
      //     id: 1,
      //     testItems: '测试',
      //     sampleName: '测试',
      //     start_date: '',
      //     end_date: '',
      //     statusC: '0',
      //   }, {
      //     id: 2,
      //     testItems: 'ceshi',
      //     sampleName: 'ceshi',
      //     start_date: '2023-07-06',
      //     end_date: '2023-07-10',
      //     statusC: '1',
      //   }, {
      //     id: 3,
      //     testItems: '测试',
      //     sampleName: '测试',
      //     start_date: '',
      //     end_date: '',
      //     statusC: '1',
      //   },{
      //     id: 4,
      //     testItems: '测试',
      //     sampleName: '测试',
      //     start_date: '',
      //     end_date: '',
      //     statusC: '1',
      //   },
      //   {
      //     id: 5,
      //     testItems: '测试',
      //     sampleName: '测试',
      //     start_date: '',
      //     end_date: '',
      //     statusC: '1',
      //   },
      //   {
      //     id: 6,
      //     testItems: '测试',
      //     sampleName: '测试',
      //     start_date: '',
      //     end_date: '',
      //     statusC: '1',
      //   },
      //   {
      //     id: 7,
      //     testItems: '测试',
      //     sampleName: '测试',
      //     start_date: '',
      //     end_date: '',
      //     statusC: '1',
      //   },
      //   {
      //     id: 8,
      //     testItems: '测试',
      //     sampleName: '测试',
      //     start_date: '',
      //     end_date: '',
      //     statusC: '1',
      //   },
      //   {
      //     id: 21,
      //     testItems: 'ceshi1',
      //     sampleName: 'ceshi',
      //     start_date: '2023-07-05',
      //     end_date: '2023-07-08',
      //     statusC: '1',
      //     pid: 2
      //   }, {
      //     id: 23,
      //     testItems: 'ceshi3',
      //     sampleName: 'ceshi',
      //     start_date: '2023-07-02',
      //     end_date: '2023-07-04',
      //     statusC: '1',
      //     pid: 2
      //   },
      //   {
      //     id: 22,
      //     testItems: 'ceshi2',
      //     sampleName: 'ceshi',
      //     start_date: '2023-07-06',
      //     end_date: '2023-07-10',
      //     statusC: '1',
      //     pid: 2
      //   }
      // ],
      // 查询条件
      queryParams: {
        weituoClient: undefined,
        weituoNo: undefined
      },
      // 委托单位下拉列表
      weituoClientOptions: [],
      // 委托编号下拉列表
      weituoNoOptions: [],
      // 试验设备下拉列表
      deviceOption: [],
      // 传感器下拉列表
      chuanganqi: [],
      // 试验类型下拉列表
      testTypeOptions: [],
      // 项目经理下拉列表
      manager: [],
      // 弹窗
      dialogVisible: false,
      title: '',
      // 弹窗内容
      currentDbEdit: {},
      // 数组中的第几个
      currentIndex: null,
      // 删除判断
      visible: false,
      // 表单校验
      rules: {
      },
      // 日历弹窗
      openRl: 1,
      showCalendarDialog: false,
      scheduleData: [],
      status: undefined,
    }
  },
  created () {
    this.getHjlist()
    this.getClientList()
    this.getDevicelist()
    this.getCgqlist()
    this.initDictConfig()
    this.getManagerList()
    // 获取设备日历
    this.getDeviceCalendar()
  },
  mounted () {
  },
  methods: {
    // 单击事件
    cellClick(row, column){
      console.log(row, column)
    },
    // 获取设备日历
    getDeviceCalendar(){
      getDeviceCalendar().then((res) =>{
        console.log(res)
        this.scheduleData = res
      })
    },
    handleEqCalendar(){
      this.openRl = -this.openRl
      // this.showCalendarDialog = true
    },
    dealMyDate(v) {
      let res = ''
      for (let index = 0; index < this.scheduleData.length; index++) {
        const element = this.scheduleData[index];
        if(element.workDate === v){
          res = this.scheduleData[index].deviceList
          break
        }
      }
      console.log(res)
      return res
    },
    // 获取委托单位下拉列表
    getClientList(){
      getWeituoClientList().then((res) =>{
        console.log(res)
        this.weituoClientOptions = res.result.map( res => {
          return{
            value: res,
            label: res
          }
        })
      })
    },
    // 监听委托单位，获取对应委托编号列表
    getWeituoClientOptions(value){
      console.log(value)
      this.weituoNoOptions = []
      this.queryParams.weituoNo = ''
      getWeituoInfoListByClient(this.queryParams).then((res) =>{
        this.weituoNoOptions = res.result.map( res => {
          return{
            value: res.weituoNo,  //传的值
            label: res.weituoNo,  //展示
          }
        })
      })
    },
    // 监听委托编号赋值
    getWeituoNoOptions(value){
      // 方法1：this.$forceUpdate() 强制刷新
      // this.$forceUpdate()
      // 方法2：
      this.queryParams = {...this.queryParams}
    },
    // 通过委托编号查询检测项目
    getHjlist(){
      let that = this
      console.log(that.queryParams)
      var queryParam = that.queryParams
      console.log(22,queryParam)
      if (queryParam.weituoClient == '' && queryParam.weituoNo == '') {
        queryParam.weituoClient = undefined
        queryParam.weituoNo = undefined
      }
      getJhList(queryParam).then((res) => {
        console.log(17,res)
        that.taskLists = []
        if (res.result.length > 0 ) {
          that.taskLists = res.result.map(res => {
            return {
              id: res.id,

              weituoId: res.weituoId,
              testItemsId: res.testItemsId,
              yangpinId:res.yangpinId,
              shebeiId:res.shebeiId,
              pm: res.pm,
              reportNo: res.reportNo,
              chuanganqiArray:res.chuanganqiArray,
              shebeiIdArray:res.shebeiIdArray,
              testPlanId:res.testPlanId,
              status:res.status,

              // text:res.reportNo,
              start_date: res.jihuaStartDate,
              end_date: res.jihuaEndDate,
              reality_startDate: res.shijiStartDate,
              reality_endDate: res.shijiEndDate,
              weituoNo: res.weituoNo,
              lastTime: res.lastTime,
              sampleName: res.sampleName,
              testItems: res.testItems,
              deviceName: res.deviceName,
              statusC: res.statusC,
              izShiji: res.izShiji,
              sampleModelSpecification: res.sampleModelSpecification,


              task_text: res.deviceName+','+res.pm,

              jhpqStatus: res.jhpqStatus
            }
          })
        }
      })
    },
    // 获取设备下拉列表
    getDevicelist(){
      getDeviceList().then((res) => {
        console.log(res)
        this.deviceOption = res.map(response =>{
          return {
            value: response.id,
            label: response.deviceName
          }
        })
      })
    },
    // 获取传感器下拉列表
    getCgqlist(){
      getCgqList().then((res) => {
        this.chuanganqi = res.map(response =>{
          return {
            key: response.id,
            value: response.id,
            label: response.xuliehao
          }
        })
      })
    },
    // 字典获取试验类型下拉列表
    initDictConfig() {
      //获取字典       你的字典名称 ⬇⬇⬇⬇
      ajaxGetDictItems('shiiyan_type').then((res) => {
        console.log('字典',res)
          this.testTypeOptions = res.result.map(response =>{
          return {
            key: response.value,
            value: response.value,
            label: response.label
          }
        })
      })
    },
    // 获取项目经理下拉列表
    getManagerList(){
      var query ={
        position: "项目经理"
      }
      getManagerList(query).then((res) => {
        this.manager = res.map(response =>{
          return {
            key: response.name,
            // value: response.id,
            value: response.name,
            label: response.name
          }
        })
      })
    },
    // 双击事件
    rowDblclick(current, a){
      console.log(current, a)
      if (current.status == 0 || current.status == null) {
        this.status = 0
      } else {
        this.status = 1
      }
      this.openRl = 1
      this.currentDbEdit = current
      this.title = this.currentDbEdit.sampleName + '-' + this.currentDbEdit.testItems + '-' + this.currentDbEdit.pm
      // 根据开始时间结束时间计算持续时间
      this.currentDbEdit.lastTime = (new Date(this.currentDbEdit.end_date).getTime() - new Date(this.currentDbEdit.start_date).getTime()) / (1000 * 60 * 60 * 24)+1
      // this.currentIndex = this.taskLists.findIndex(res=>res.id === current.id)
      // this.currentDbEdit = this.taskLists[this.currentIndex]
      this.dialogVisible = true
    },
    // 监听开始时间得到结束时间
    dataChange(value){
      console.log(value)
      let nowDate = new Date(value)
        nowDate.setDate(nowDate.getDate() + this.currentDbEdit.lastTime -1)
        console.log(nowDate)
        let y = nowDate.getFullYear()
        let m = nowDate.getMonth() + 1
        m = m < 10 ? ('0' + m) : m
        let d = nowDate.getDate()
        d = d < 10 ? ('0' + d) : d
        this.currentDbEdit.end_date = y + '-' + m + '-' + d;
        return this.currentDbEdit.end_date
    },
    // 监听持续时间得到结束时间
    handleChange(value) {
      console.log(value,this.currentDbEdit.start_date);
      let nowDate = new Date(this.currentDbEdit.start_date)
          nowDate.setDate(nowDate.getDate() + value -1)
          console.log(nowDate)
          let y = nowDate.getFullYear()
          let m = nowDate.getMonth() + 1
          m = m < 10 ? ('0' + m) : m
          let d = nowDate.getDate()
          d = d < 10 ? ('0' + d) : d
          this.currentDbEdit.end_date = y + '-' + m + '-' + d;
          return this.currentDbEdit.end_date
    },
    // 删除
    remove(){
      console.log(this.currentDbEdit.id)
      if (this.currentDbEdit.statusC == "不可修改"){
          this.$message.error('该项已进行，不可修改');
          this.visible = false
      }else{
        var select={id: this.currentDbEdit.id}
          delProjectJl(select).then((res) => {
            console.log("删除",res)
            if (res.success) {
              this.$message.success('删除成功');
              this.dialogVisible = false
              this.currentDbEdit = {}
              this.getHjlist()
            }
          })
      }
    },
    cancel(){
      this.currentDbEdit = {}
      this.dialogVisible = false
    },
    submit(){
      // this.taskLists[this.currentIndex].start_date = this.currentDbEdit.start_date
      // this.taskLists[this.currentIndex].end_date = this.currentDbEdit.end_date
      // this.dialogVisible = false
      // this.currentDbEdit = {}
      console.log(this.currentDbEdit)
      this.currentDbEdit.jihuaStartDate = this.currentDbEdit.start_date ;
      this.currentDbEdit.jihuaEndDate = this.currentDbEdit.end_date ;
      this.currentDbEdit.parent = this.currentDbEdit.pid ;
      saveProject(this.currentDbEdit).then((res) => {
        console.log("提交返回",res)
        if (res.success) {
          this.$message.success('提交成功');
          this.dialogVisible = false
          this.currentDbEdit = {}
          this.getHjlist()
        }
      })
    },
  }
}
</script>

<style lang="scss">
.gdPlan-container{
  ::v-deep .el-table th.el-table__cell>.cell{
    padding-left: 0;
    padding-right: 0;
  }
  ::v-deep .el-table .cell{
    padding-left: 0;
    padding-right: 0;
  }
  .eq-rili-view{
    .el-select{
      .el-input__inner{
        border-top-right-radius: 0 !important;
        border-bottom-right-radius: 0 !important;
        border-right: 0 !important;
      }
    }
    .search-btn{
      width: 60px;
      background-color: #1890ff;
      // padding: 0 22px;
      color: #fff;
      border-top-right-radius: 4px;
      border-bottom-right-radius: 4px;
      text-align: center;
    }
  }
  // 日历
  .el-calendar{
    .el-calendar-table .el-calendar-day{
      padding: 0;
      min-height: 65px;
      height: 100%;
      .weeked{
        text-align: center;
      }
      .notweeked{
        text-align: center;
      }
    }
    .eqCalendar-item{
      // width: ;
      background-color: #EBF4FE;
      position: relative;
      padding: 2px 6px;
      font-size: 12px;
      margin-bottom: 4px;
      overflow: auto;
    }
    .eqCalendar-item::after{
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      width: 2px;
      height: 100%;
      background-color: #4F9AF6;
    }
  }
}
</style>
