<template>
  <div class="gdDetail-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" @addRow="addRow" @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" v-if="currentDbEdit.pid == null">
            <el-input v-model="currentDbEdit.reportNo" placeholder="请输入报告编号"></el-input>
          </el-form-item> -->
          <el-form-item label="试验设备" prop="shebeiIdArray" v-if="currentDbEdit.pid == null">
            <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-form-item label="试验设备" prop="shebeiId" v-if="currentDbEdit.pid != null">
            <div class="eq-rili-view" style="display: flex;">
              <el-select v-model="currentDbEdit.shebeiId" placeholder="请选择试验设备" style="width: 100%;">
                <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="shiiyanTypeArray" v-if="currentDbEdit.pid != null">
            <el-select v-model="currentDbEdit.shiiyanTypeArray" multiple placeholder="请选择试验类型" style="width: 100%;">
              <el-option
                v-for="item in testTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="操作员" prop="worker" v-if="currentDbEdit.pid != null">
            <el-select v-model="currentDbEdit.worker" placeholder="请选择操作员" style="width: 100%;">
              <el-option
                v-for="item in worker"
                :key="item.label"
                :label="item.label"
                :value="item.label">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="样品数量" prop="yangpinCount" v-if="currentDbEdit.pid != null">
            <el-input-number v-model="currentDbEdit.yangpinCount" :min="1"></el-input-number>
          </el-form-item>
          <el-form-item label="内容" prop="neirong" v-if="currentDbEdit.pid != null">
            <el-input type="textarea" autosize placeholder="请输入内容" v-model="currentDbEdit.neirong">
            </el-input>
          </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/> -->
        <!-- 日历弹窗 -->
        <el-dialog title="设备日历" :visible.sync="showCalendarDialog" width="60%" append-to-body>
          <el-calendar>
            <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)">
                    <template v-for="(item, index) in dealMyDate(data.day)">
                      <el-tag type="danger" :key="index" style="margin-right: 2px;" @click="chooseDevice(item)">
                        {{ item.deviceName }}
                      </el-tag>
                    </template>
                  </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>
          <span slot="footer" class="dialog-footer">
            <el-button @click="showCalendarDialog = false">取 消</el-button>
            <el-button type="primary" @click="showCalendarDialog = false">确 定</el-button>
          </span>
        </el-dialog>
        <span slot="footer" class="dialog-footer">
          <el-popover
            style="margin-right: 10px;"
            placement="top"
            width="160"
            v-model="visible"
            v-if="currentDbEdit.pid != null && this.typeButton != 1">
            <p>确定删除改任务吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="visible = false">取消</el-button>
              <el-button type="primary" size="mini" @click="remove">确定</el-button>
            </div>
            <el-button slot="reference">删 除</el-button>
          </el-popover>
          <!-- <el-button @click="remove">删 除</el-button> -->
          <el-button @click="cancel">关 闭</el-button>
          <el-button type="primary" @click="submit" v-if="currentDbEdit.pid != null">确 定</el-button>
        </span>
      </el-dialog>
    </uGantt>
    <itdm-weituo-info-modal ref="modalForm1"></itdm-weituo-info-modal>
    <!-- <u-gantt-dialog ref="dialogForm"></u-gantt-dialog> -->
  </div>
</template>

<script>
import uGantt from '@/components/module-iTDM/uGantt/index.vue'
import {getWeituoClientList, getWeituoInfoListByClient, getDeviceList, getXmjlList, getManagerList, getCgqList, saveProject, ajaxGetDictItems, saveProjectJl, delProjectJl, getDeviceCalendar} from '@/api/api'
import UGanttDialog from './modules/uGanttDialog.vue'
import ItdmWeituoInfoModal from '../weituo/modules/ItdmWeituoInfoModal.vue'
  import { httpAction, getAction } from '@/api/manage'
export default {
  name: '',
  components: { uGantt,UGanttDialog, ItdmWeituoInfoModal },
  data () {
    return {
      // 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: "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: {},
      // 委托单位下拉列表
      weituoClientOptions: [],
      // 委托编号下拉列表
      weituoNoOptions: [],
      // 试验设备下拉列表
      deviceOption: [],
      // 传感器下拉列表
      chuanganqi: [],
      // 试验类型下拉列表
      testTypeOptions: [],
      // 操作员下拉列表
      worker: [],
      // 弹窗
      dialogVisible: false,
      title: '',
      // 弹窗内容
      currentDbEdit: {},
      // 数组中的第几个
      currentIndex: null,
      // 删除判断
      visible: false,
      // 点击按钮判断
      typeButton: null,
      // 表单校验
      rules: {
      },
      // 日历弹窗
      openRl: 1,
      showCalendarDialog: false,
      scheduleData: [],
      // 委托详情数据
      record: {},
      url: {
        queryById: "/weituo/itdmWeituoInfo/queryById"
      }
    }
  },
  created () {
    this.getClientList()
    this.getDevicelist()
    this.getCgqlist()
    this.initDictConfig()
    this.getManagerList()
    // 获取设备日历
    this.getDeviceCalendar()
  },
  mounted () {
  },
  methods: {
    // 单击事件
    cellClick(row, column){
      console.log(row.weituoId, column.label)
      if (column.label == '委托编号') {
        let httpurl = '';
        httpurl+=this.url.queryById;
        const id = {id:row.weituoId}
        getAction(httpurl,id).then((res)=>{
          console.log(res)
          this.record = res.result
          this.$refs.modalForm1.edit(this.record);
          this.$refs.modalForm1.title="委托详情";
          this.$refs.modalForm1.disableSubmit = true;
        }).finally(() => {
          // that.confirmLoading = false;
        })
        // this.$refs.dialogForm.open();
      }
    },
    // 获取设备日历
    getDeviceCalendar(){
      getDeviceCalendar().then((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
      var queryParam = that.queryParams
      console.log(22,queryParam)
      getXmjlList(queryParam).then((res) => {
        console.log(17,res)
        that.taskLists = []
        if (res.result.length > 0 ) {
          that.taskLists = res.result.map(res => {
            var obj = res
            obj.pid = res.parent
            obj.start_date = res.jihuaStartDate
            obj.end_date = res.jihuaEndDate
            if (obj.pid == null){
              obj.task_text= res.deviceName+','+res.pm
            } else {
              obj.task_text= res.deviceName+','+res.worker
            }
            return obj
          })
          console.log(that.taskLists)
        }
        // else {
        //   notification.open({
        //     message: '注意',
        //     description: '该委托编号不存在',
        //   });
        // }
      })
    },
    // 获取设备下拉列表
    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.worker = res.map(response =>{
          return {
            key: response.name,
            value: response.id,
            label: response.name
          }
        })
       // this.initData()
      })
    },
    // 双击事件
    rowDblclick(current){
      console.log(current)
      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
    },
    // 新增事件
    addRow(row, index){
      this.typeButton = 1
      console.log(row, index)
      this.currentDbEdit = JSON.parse(JSON.stringify(row))
      this.currentDbEdit.parent = row.id
      this.currentDbEdit.pid = row.id
      this.dialogVisible = true
    },
    // 删除
    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.typeButton = null
              this.dialogVisible = false
              this.currentDbEdit = {}
              this.getHjlist()
            }
          })
      }
    },
    cancel(){
      this.currentDbEdit = {}
      this.typeButton = null
      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)
      if (this.currentDbEdit.status == 3 || this.currentDbEdit.status == 1) {
        this.currentDbEdit.jihuaStartDate = this.currentDbEdit.start_date ;
        this.currentDbEdit.parent = this.currentDbEdit.pid ;
        saveProjectJl(this.currentDbEdit).then((res) => {
          console.log("提交返回",res)
          if (res.success) {
            this.$message.success('提交成功');
            this.typeButton = null
            this.dialogVisible = false
            this.currentDbEdit = {}
            this.getHjlist()
          }
        })
      } else {
        this.$message.error('不可修改');
      }
    },
  }
}
</script>

<style lang="scss">
.gdDetail-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;
        border-bottom-right-radius: 0;
        border-right: 0;
      }
    }
    .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>
