<template>
  <div>
    <el-card>
      <div slot="header" class="clearfix">
        <div class="fr">
          <el-button size="mini" type="primary" @click.native="saveOrder(1)" :loading="draftLoading"
          >草稿保存
          </el-button>
          <el-button size="mini" type="primary" @click.native="saveOrder(2)"  :loading="submitLoading"
          >立即提交
          </el-button>
        </div>
      </div>
      <el-form :model="planData" :rules="formRule" ref="dataForm" label-width="auto">
        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="计划名称" prop="name">
              <el-input v-model.trim="planData.name" show-word-limit maxlength="100" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="负责部门" prop="chargeDeptCode">
              <deptSelect :value.sync="planData.chargeDeptCode"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="执行区间" prop="dateInterval">
              <el-date-picker
                style="width: 100%"
                v-model.trim="planData.dateInterval"
                type="daterange"
                align="right"
                editable
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item prop="frequency">
              <template slot="label">
                执行频率
              </template>
              <el-input-number :min="1" :max="999999" v-model.trim="planData.frequency"/>
              <span class="ml10">天
                 <el-tooltip class="item" effect="dark" content="执行频率（次），例：每30天执行一次"
                             placement="top">
                  <el-icon class="el-icon-question"/>
                </el-tooltip></span>
              <!--              <span class="ml10">快捷选项：</span>-->
              <!--              <el-button type="" @click="planData.frequency=30">一个月</el-button>-->
              <!--              <el-button type="" @click="planData.frequency=30*3">三个月</el-button>-->
              <!--              <el-button type="" @click="planData.frequency=30*6">半年</el-button>-->
              <!--              <el-button type="" @click="planData.frequency=365">一年</el-button>-->
              <!--              <el-button type="" @click="planData.frequency=365*2">两年</el-button>-->
              <!--              <el-button type="" @click="planData.frequency=365*3">三年</el-button>-->
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="备注">
              <el-input type="textarea" v-model.trim="planData.remark" resize="none" :autosize="{minRows:1,maxRows:8}"
                        show-word-limit maxlength="500" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card>
      <div slot="header" class="clearfix">
        <div class="fr">
          <el-button type="primary" @click="addDevice()">添加设备</el-button>
          <el-button type="primary" @click="batchSetProject()">
            <div v-if="this.originData.type == 2">批量设置保养项目</div>
            <div v-else>批量设置巡检项目</div>
          </el-button>
          <el-button type="" @click="getDetailList">刷新</el-button>
        </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="scope">
            <el-button type="text" @click="setProject(scope.row)"
            >
              <div v-if="originData.type == 2">保养项目</div>
              <div v-else>巡检项目</div>
            </el-button>
            <el-button type="text" @click="delProject(scope.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="添加设备"
      :visible="true"
      v-if="chooseDeviceFlag"
      @close="chooseDeviceFlag = false"
      width="80%"
    >
      <DeviceAdd style="margin: 0"
                 :planId="detailQuery.planId"
                 :planData="planData"
                 :pullData="originData"
                 :closeAddDevice="closeAddDevice"/>
    </el-dialog>

    <el-dialog
      :title="formMap1[formName1]"
      :visible="true"
      v-if="projectVisible"
      @close="projectVisible = false"
      width="80%"
    >
      <DevicePlanProject style="margin: 0"
                         :planId="detailQuery.planId"
                         :projectItem="projectItem"
                         :pullData="originData"
                         :closeAddDevice="closeAddDevice"/>
    </el-dialog>


    <el-dialog
      :title="formMap[formName]"
      :visible="true"
      v-if="chooseDetailItemFlag"
      @close="chooseDetailItemFlag = false"
      width="80%"
    >
      <deviceProjectAdd style="margin: 0"
                        :planId="planData.planId"
                        :type="2"
                        :pullData="originData"
                        :closeAddDevice="closeBatchSetProject"/>
    </el-dialog>

  </div>
</template>

<script>
import {
  devicePlanDetailAdd, devicePlanDetailDel,
  devicePlanDetailDelByDeviceCode,
  devicePlanDetailPage
} from "@/api/dev/devicePlanDetailApi";
import {getLoading} from "@/utils";
import DeviceAdd from "@/views/dev/deviceAdd";
import {devicePlanDetailItemAdd} from "@/api/dev/devicePlanDetailItemApi";
import DevicePlanProject from "@/views/dev/devicePlanProject";
import {devicePlanSave} from "@/api/dev/devicePlanApi";
import {deviceUpkeepPlanSave} from "@/api/dev/deviceUpkeepPlanApi";
import deviceProjectAdd from "@/views/dev/deviceProjectAdd";
import { isBlank } from '@/utils/strUtil'

export default {
  name: "devicePlanEdit",
  components: {DevicePlanProject, DeviceAdd, deviceProjectAdd},
  props: {
    originData: {
      type: Object,
      required: true
    },
    closePlanEdit: {required: false, type: Function}
  },
  data() {
    return {
      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"]
        }],
      },
      formName:2,
      formMap: {
        1: "批量设置巡检项目",
        2: "批量设置保养项目"
      },
      formName1:2,
      formMap1: {
        1: "添加巡检项目",
        2: "添加保养项目"
      },
      detailList: [],
      detailTotal: 0,
      detailQuery: {
        type : this.originData.type
      },
      detailLoading: false,
      chooseDeviceList: [],
      chooseDeviceFlag: false,
      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]);
          }
        }]
      },
      chooseItemList: [],

      //巡检项目
      projectVisible: false,
      projectItem: null,
      chooseDetailItemFlag: false,
      draftLoading: false,
      submitLoading: false,
    }
  },

  methods: {
    getDetailList() {
      if (this.detailQuery.planId != null){
        this.detailLoading = true
        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
        })
      }
    },

    addDevice() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          if(this.originData.type === 1) {
            this.formName = 1
            this.originData = {
              type:1
            }
          }
          this.chooseDeviceFlag = true
        }
      });
    },
    closeAddDevice(data) {
      this.chooseDeviceFlag = false
      this.planData = data
      this.detailQuery.planId = data.planId
      this.getDetailList()
    },

    batchSetProject() {
      if(this.originData.type === 1) {
        this.formName = 1
        this.originData = {
          type:1
        }
      }
      if(isBlank(this.planData.planId)){
        this.$message.error("请先添加设备")
      }else {
        this.chooseDetailItemFlag = true;
      }

    },
    closeBatchSetProject() {
      this.chooseDetailItemFlag = false;
    },


    setProject(row) {
      if (this.originData.type === 1){
        this.formName1 = 1
        this.originData = {
          type:1
        }
      }
      this.projectVisible = true
      this.projectItem = row
    },

    delProject(row) {
      this.$confirm("此操作将会永久删除该条明细，且将在下一次任务生效，现有任务不受影响，是否继续", "提示", {
        confirmButtonText: "继续",
        cancelButtonText: "取消"
      }).then(() => {
        let load = getLoading(this)
        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()
        })
      })
    },

    saveOrder(status) {
      this.planData.status = status;
      this.planData.type = this.originData.type;
      if (status == 1){
        //草稿保存
        this.draftLoading = true
      }else {
        this.submitLoading = true
      }
      if (this.$parent.$options.propsData.title == '新增保养计划'){
        deviceUpkeepPlanSave(this.planData).then(res => {
          if (status == 1){
            //草稿保存
            this.draftLoading = false
          }else {
            this.submitLoading = false
          }
          if (res.code != 20000) {
            this.$message.error(res.message)
            return
          }
          this.closePlanEdit();
          this.$message.success("保存成功！")
        }).catch(e => {
        })
      }else {
        devicePlanSave(this.planData).then(res => {
          if (status == 1){
            //草稿保存
            this.draftLoading = false
          }else {
            this.submitLoading = false
          }
          if (res.code != 20000) {
            this.$message.error(res.message)
            return
          }
          this.closePlanEdit();
          this.$message.success("保存成功！")
        }).catch(e => {
        })
      }

    },

    chooseDevice(multiData) {
      let loading = getLoading(this)
      let param = {
        planId: this.planData.planId,
        deviceCodes: multiData
      }
      devicePlanDetailAdd(param).then(res => {
        loading.close()
        if (res.code != 20000) {
          this.$message.error(res.message)
          return
        }
        this.chooseDeviceList = []
        this.$message.success(res.message)
        this.chooseDeviceFlag = false
        this.detailQuery.page = 1
        this.getDetailList()

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


  },

  created() {
    if (this.originData != null) {
      this.planData = this.originData;
    }
    this.detailQuery = {
      planId: this.planData.planId,
      page: 1,
      limit: 10
    }
    this.getDetailList()
  },

  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()
    }
  },
}
</script>

<style scoped>

</style>
