<template>
  <div>
    <!--    巡检计划主表-->
    <el-card>
      <el-form :model="query" v-if="showSearch" label-width="auto">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="计划名称">
              <el-input v-model.trim="query.name" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="负责部门">
              <deptSelect :value.sync="query.chargeDeptCode"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="top-right-btn">
        <el-button-group>
          <el-button icon="el-icon-view" type="primary" @click="showSearch = !showSearch">显示/隐藏搜索栏</el-button>
          <el-button
            type="primary"
            icon="el-icon-refresh"
            @click="onReset"
          >重置
          </el-button>
          <el-button type="primary" icon="el-icon-search" @click="search"
          >查询
          </el-button>
          <el-button type="primary" icon="el-icon-plus" @click="openCreate(null,null)"
          >新增
          </el-button>
        </el-button-group>
      </div>
      <el-divider style="margin: 15px"></el-divider>
      <el-table :data="list" @row-click="rowClick" v-loading="loading" click-row-light
                highlight-current-row
      >
        <el-table-column label="序号" width="50" type="index"/>
        <el-table-column label="计划单号" width="150" prop="planBillNo"/>
        <el-table-column label="计划名称" width="150" prop="name"/>
        <el-table-column label="负责部门" width="120" prop="chargeDeptName"/>
        <el-table-column label="设备数量" width="120" prop="deviceCount"/>
        <el-table-column label="单据状态" width="120" prop="chargeDeptName">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status==1" type="warning">草稿</el-tag>
            <el-tag v-if="scope.row.status==2" type="success">已提交</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="执行状态" width="120" prop="chargeDeptName">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.isActive==true" type="success">执行中</el-tag>
            <el-tag v-if="scope.row.isActive==false" type="info">未执行</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="开始日期" width="150" prop="startDate"/>
        <el-table-column label="结束日期" width="150" prop="endDate"/>
        <el-table-column label="执行频率" width="160" prop="frequency">
          <template slot-scope="scope">
            {{ `${scope.row.frequency}天` }}
          </template>
        </el-table-column>
        <el-table-column label="已执行次数" width="200" prop="execCount"/>
        <el-table-column label="备注" width="200" prop="remark"/>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" @click.stop="openCreate(scope.row.planId,scope.row)">
              编辑
            </el-button>
            <el-button type="text" @click="deviceCheckGenFunc(scope.row)"
            >生成任务单
            </el-button>
            <el-button type="text" @click.stop="delplan(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="query.page"
        :limit.sync="query.limit"
        @pagination="getList"
      />
    </el-card>

    <!--    巡检计划设备明细-->
    <el-card>
      <div slot="header" class="clearfix">
        <div class="fl">
          {{ `计划详情 ${clickRow ? '——' + clickRow.name : ''}` }}
        </div>
      </div>
      <el-table :data="detailList"
                v-loading="detailLoading" click-row-light
                highlight-current-row
      >
        <el-table-column label="序号" width="50" type="index"/>
        <el-table-column label="科室名称" prop="deptName"/>
        <el-table-column label="设备编号" prop="deviceCode"/>
        <el-table-column label="最小销售标识" prop="nameCode"/>
        <el-table-column label="名称" prop="productName"/>
        <el-table-column label="规格型号" prop="ggxh"/>
        <el-table-column label="计量单位" prop="measname"/>
        <el-table-column label="生产企业" prop="manufactory"/>
        <el-table-column label="注册/备案号" prop="zczbhhzbapzbh"/>
        <el-table-column label="操作" width="120">
          <template slot-scope="prop">
            <el-button type="text" @click="setProject(prop.row)"
            >巡检项目
            </el-button>
            <!--            <el-button type="text" @click="delDetail(prop.row)"-->
            <!--            >移除-->
            <!--            </el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="detailTotal>0"
        :total="detailTotal"
        :page.sync="detailQuery.page"
        :limit.sync="detailQuery.limit"
        @pagination="getDetailList"
      />
    </el-card>


    <el-dialog
      :title="planEditTitle"
      :visible="true"
      v-if="createFlag"
      @close="createFlag = false"
      width="80%"
    >
      <devicePlanEdit :originData="planData"
                      :closePlanEdit="closePlanEdit"
                      :createFlag="createFlag"
      />
    </el-dialog>


    <el-dialog
      title="编辑巡检项目"
      :visible="true"
      v-if="projectVisible"
      @close="projectVisible = false"
      width="80%"
    >
      <DevicePlanProject style="margin: 0"
                         :planId="detailQuery.planId"
                         :projectItem="projectItem"
                         :pullData="planData"
                         :closeAddDevice="closeAddDevice"
      />
    </el-dialog>


  </div>

</template>


<script>
import { devicePlanDel, devicePlanInfo, devicePlanPage, devicePlanSave } from '@/api/dev/devicePlanApi'
import {
  devicePlanDetailDel,
  devicePlanDetailPage, devicePlanDetailDelByDeviceCode
} from '@/api/dev/devicePlanDetailApi'
import { getLoading } from '@/utils'
import product from '@/views/basic/product/product.vue'
import {
  devicePlanDetailItemAdd, devicePlanDetailItemByDeviceCodeDel,
  devicePlanDetailItemDel,
  devicePlanDetailItemPage
} from '@/api/dev/devicePlanDetailItemApi'
import DeviceCheckItemDict from '@/views/dev/deviceCheckItemDict'
import { deviceCheckGenByPlanId } from '@/api/dev/deviceCheckApi'

import DevicePlanProject from '@/views/dev/devicePlanProject'
import devicePlanEdit from '@/views/dev/devicePlanEdit'

let query = {
  page: 1,
  limit: 10,
  name: null,
  chargeDeptCode: null,
  type: 1
}

let detailQuery = {
  page: 1,
  limit: 10,
  planId: null
}
let rowDeltailQuery = {
  page: 1,
  limit: 10,
  planId: null,
  productId: null
}

let itemQuery = {
  page: 1,
  limit: 10,
  planId: null,
  productId: null
}

let planData = {
  planId: null,
  name: null,
  chargeDeptCode: null,
  startDate: null,
  endDate: null,
  frequency: 1,
  dateInterval: null,
  remark: null,
  type: 1
}

export default {
  name: 'devicePlan',
  components: { DeviceCheckItemDict, product, devicePlanEdit, DevicePlanProject },
  computed: {},
  data() {
    return {
      clickRow: null,
      showSearch: true,
      loading: false,
      total: .0,
      list: [],
      query: { ...query },
      //计划设备明细=============================================
      detailLoading: false,
      detailQuery: { ...detailQuery },
      detailList: [],
      detailTotal: 0,
      //巡检项目=============================================
      itemQuery: { ...itemQuery },
      itemList: [],
      itemTotal: 0,
      itemLoading: false,
      chooseDetailItemFlag: false,
      chooseDeviceList: [],
      chooseItemList: [],
      //新增/编辑计划===================================================
      planEditTitle: '新增计划',
      createActive: 0,
      createFlag: false,
      chooseDeviceFlag: false,
      expandRowKeys: [],
      dialogExpandRowKeys: [],
      planData: { ...planData },
      formRule: {
        name: [{ required: true, message: '计划名称不能为空', trigger: ['change', 'blur'] }],
        chargeDeptCode: [{ required: true, message: '负责部门不能为空', trigger: ['change', 'blur'] }],
        dateInterval: [{ required: true, message: '计划执行区间不能为空', trigger: ['change', 'blur'] }],
        frequency: [{
          required: true,
          message: '计划执行频率不能为空',
          trigger: ['change', 'blur']
        }]
      },
      dateInterval: null,
      pickerOptions: {
        disabledDate: time => {
          let nowDate = new Date().getTime()
          let pickDate = new Date(time).getTime()
          return (nowDate >= pickDate)
        },
        shortcuts: [{
          text: '一个月(30天)',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() + 3600 * 1000 * 24)
            end.setTime(start.getTime() + 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '三个月(90天)',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() + 3600 * 1000 * 24)
            end.setTime(start.getTime() + 3600 * 1000 * 24 * 30 * 3)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '半年(180天)',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() + 3600 * 1000 * 24)
            end.setTime(start.getTime() + 3600 * 1000 * 24 * 30 * 6)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '一年(365天)',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() + 3600 * 1000 * 24)
            end.setTime(start.getTime() + 3600 * 1000 * 24 * 365)
            picker.$emit('pick', [start, end])
          }
        }]
      },

      projectVisible: false,
      projectItem: null
    }
  },
  watch: {
    planData(v) {
      if (v.planId != null) {
        this.$set(v, 'dateInterval', [v.startDate, v.endDate])
      }
    },
    'planData.dateInterval'(v) {
      if (v != null && v.length > 0) {
        this.planData.startDate = v[0]
        this.planData.endDate = v[1]
      }
    },
    '$refs.dialogTable'(v) {

      this.$refs.dialogTable?.doLayout()
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleExpendRow(row, expandedRows) {
      if (expandedRows.length == 0) {
        return
      }
      this.$set(row, 'detailData', {
        loading: false,
        showSearch: true,
        list: [],
        total: 0,
        query: { ...rowDeltailQuery, planId: row.planId, productId: row.productId }
      })
      this.getRowDetailList(row.detailData)
    },
    getRowDetailList(data) {
      data.loading = true
      devicePlanDetailPage(data.query).then(res => {
        data.loading = false
        if (res.code != 20000) {
          this.$message.error(res.message)
          return
        }
        data.list = res.data.list || []
        data.total = res.data.total || 0

      }).catch(() => {
        data.loading = false
        data.list = []
        data.total = 0
      })
    },
    deviceCheckGenFunc(row) {
      this.$confirm('此操作将会创建一个任务单，是否继续', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消'
      }).then(() => {
        let load = getLoading(this)
        deviceCheckGenByPlanId(row.planId).then(res => {
          load.close()
          if (res.code != 20000) {
            this.$message.error(res.message)
            return
          }
          this.$message.success(res.message)
          this.getList()

        }).catch(() => {
          load.close()
        })
      })
    },
    delplan(row) {
      this.$confirm('此操作将会永久删除该计划，现有任务不受影响，是否继续', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消'
      }).then(() => {
        let load = getLoading(this)
        devicePlanDel(row.planId).then(res => {
          load.close()
          if (res.code != 20000) {
            this.$message.error(res.message)
            return
          }
          this.$message.success(res.message)
          this.query.page = 1
          this.getList()
          if (this.clickRow && this.clickRow.planId == row.planId) {
            this.clickRow = null
            this.detailTotal = 0
            this.detailList = []
          }
        }).catch(() => {
          load.close()
        })
      })
    },
    openItem(row) {
      this.itemQuery = {
        ...itemQuery,
        planId: row.planId,
        productId: row.productId,
        deviceCode: row.deviceCode,
        title: `${row.deviceCode ? row.deviceCode + '--' : ''}${row.productName}(${row.nameCode})`
      }
      this.getDetailItemList()
    },
    getDetailItemList() {
      this.itemLoading = true
      devicePlanDetailItemPage(this.itemQuery).then(res => {
        this.itemLoading = false
        if (res.code != 20000) {
          this.$message.error(res.message)
          return
        }
        this.itemList = res.data.list || []
        this.itemTotal = res.data.total || 0
      }).catch(e => {
        this.itemList = []
        this.itemTotal = 0
        this.itemLoading = false
      })
    },
    delDetailItem(row) {
      this.$confirm('此操作将会永久删除该条明细，且将在下一次任务生效，现有任务不受影响，是否继续', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消'
      }).then(() => {
        let load = getLoading(this)
        if (!row.deviceCode) {
          devicePlanDetailItemDel(row.planId, row.productId, row.itemCode).then(res => {
            load.close()
            if (res.code != 20000) {
              this.$message.error(res.message)
              return
            }
            this.$message.success(res.message)
            this.itemQuery.page = 1
            this.getDetailItemList()
          }).catch(() => {
            load.close()
          })
        } else {
          devicePlanDetailItemByDeviceCodeDel(row.planId, row.deviceCode, row.itemCode).then(res => {
            load.close()
            if (res.code != 20000) {
              this.$message.error(res.message)
              return
            }
            this.$message.success(res.message)
            this.itemQuery.page = 1
            this.getDetailItemList()
          }).catch(() => {
            load.close()
          })
        }
      })
    },
    delDetail(row) {
      this.$confirm('此操作将会永久删除该条明细，且将在下一次任务生效，现有任务不受影响，是否继续', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消'
      }).then(() => {
        let load = getLoading(this)
        if (row.deviceCode) {
          devicePlanDetailDelByDeviceCode(row.planId, row.deviceCode).then(res => {
            load.close()
            if (res.code != 20000) {
              this.$message.error(res.message)
              return
            }
            this.$message.success(res.message)
            this.detailQuery.page = 1
            this.getDetailList()
          }).catch(() => {
            load.close()
          })
        } else {
          devicePlanDetailDel(row.planId, row.productId).then(res => {
            load.close()
            if (res.code != 20000) {
              this.$message.error(res.message)
              return
            }
            this.$message.success(res.message)
            this.detailQuery.page = 1
            this.getDetailList()
          }).catch(() => {
            load.close()
          })
        }

      })
    },
    rowClick(row) {
      this.clickRow = row
      this.detailQuery = { ...detailQuery, planId: row.planId }
      this.getDetailList()
    },
    getDetailList() {
      this.detailLoading = true
      this.expandRowKeys = []
      this.dialogExpandRowKeys = []
      devicePlanDetailPage(this.detailQuery).then(res => {
        this.detailLoading = false
        if (res.code != 20000) {
          this.$message.error(res.message)
          return
        }
        this.detailList = res.data.list || []
        this.detailTotal = res.data.total || 0
      }).catch(e => {
        this.detailList = []
        this.detailTotal = 0
        this.detailLoading = false
      })
    },
    changeActive(isNext, row) {
      let load = getLoading(this)
      if (isNext) {
        if (this.createActive == 0) {
          this.$refs.saveForm.validate(b => {
            if (!b) {
              load.close()
              return
            }
            devicePlanSave(this.planData).then(res => {
              load.close()
              if (res.code != 20000) {
                this.$message.error(res.message)
                return
              }
              this.planData.planId = res.data
              this.detailQuery = { ...detailQuery, planId: this.planData.planId }
              this.getDetailList()
              this.createActive += 1
            }).catch(e => {
              load.close()
            })
          })
        } else if (this.createActive == 1) {
          this.openItem(row)
          load.close()
          this.createActive += 1
        }

      } else {
        if (this.createActive == 2) {
          this.planData = { ...this.planData }
          this.detailQuery = { ...detailQuery, planId: this.itemQuery.planId }
          this.getDetailList()
          load.close()
          this.createActive -= 1
        } else if (this.createActive == 1) {
          devicePlanInfo(this.planData.planId).then(res => {
            load.close()
            if (res.code != 20000) {
              this.$message.error(res.message)
              return
            }
            this.planData = { ...res.data }
            this.createActive -= 1
          }).catch(e => {
            load.close()
          })
        }
      }
      load.close()
    },
    itemSelectChangFunc(list) {
      this.chooseItemList = list.map(i => i.code)
    },
    chooseDetailItem() {
      let loading = getLoading(this)
      let param = {
        planId: this.itemQuery.planId,
        productId: this.itemQuery.productId,
        deviceCode: this.itemQuery.deviceCode,
        itemCodes: this.chooseItemList
      }
      devicePlanDetailItemAdd(param).then(res => {
        loading.close()
        if (res.code != 20000) {
          this.$message.error(res.message)
          return
        }
        this.chooseItemList = []
        this.$message.success(res.message)
        this.chooseDetailItemFlag = false
        this.itemQuery.page = 1
        this.getDetailItemList()

      }).catch(e => {
        loading.close()
      })
    },

    closePlanEdit() {
      this.createFlag = false
      this.getList()
    },

    deviceSelectChangFunc(list) {
      this.chooseDeviceList = list.map(i => i.deviceCode)
    },

    //新增编辑计划
    openCreate(planId, row) {
      if (planId != null) {
        this.planEditTitle = `编辑巡检计划信息${row.planId ? '--(' + row.name + ')' : ''}`
        this.planData = row
      } else {
        this.planEditTitle = '新增计划'
        this.planData = {
          type: 1
        }
      }
      this.createFlag = true

      // this.createActive = 0
      // if (createActive != null) {
      //   this.createActive = createActive
      // }
      // if (planId != null) {
      //   devicePlanInfo(planId).then(res => {
      //     if (res.code != 20000) {
      //       this.$message.error(res.message)
      //       return
      //     }
      //     this.planData = {...res.data}
      //     this.createFlag = true
      //     if (createActive == 1) {
      //       this.detailQuery = {...detailQuery, planId: planId}
      //       this.getDetailList()
      //     } else if (createActive == 2) {
      //       this.itemQuery = {
      //         ...detailQuery,
      //         planId: planId,
      //         productId: row.productId,
      //         deviceCode: row.deviceCode,
      //         title: `${row.deviceCode ? row.deviceCode + '--' : ''}${row.productName}(${row.nameCode})`
      //       }
      //       this.getDetailItemList()
      //     }
      //   })
      // } else {
      //   this.planData = {...planData}
      //   this.createFlag = true
      // }
    },
    search() {
      this.query.page = 1
      this.getList()
    },
    onReset() {
      this.query = { ...query }
      this.getList()
    },
    getList() {
      this.loading = true
      // console.log("yuepe",this.query)
      devicePlanPage(this.query).then(res => {
        this.loading = false
        if (res.code != 20000) {
          this.$message.error(res.message)
          return
        }
        this.list = res.data.list || []
        this.total = res.data.total || 0

      }).catch(e => {
        this.loading = false
      })
    },
    setProject(row) {
      this.planData = {
        type: 1
      }
      this.projectVisible = true
      this.projectItem = row
    }
  }
}


</script>


<style scoped>

/deep/ .el-dialog__body {
  padding: 0 0 20px 0;
}
</style>
