<template>
  <div>
    <el-row class="row">
      <el-col :span="5">
        <span class="machineClass">机号:</span>
        <el-select style="width:100px" v-model="forms.bed">
          <el-option
            v-for="item in this.bedNumber"
            :key="item.id"
            :label="item.number"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-col>
      <el-col :span="11">
        <span class="machineClass">日期查询:</span>
        <el-date-picker
          v-model="forms.start_time"
          prefix-icon="none"
          type="date"
          placeholder="请选择"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          style="width:150px"
        ></el-date-picker
        >-
        <el-date-picker
          v-model="forms.end_time"
          prefix-icon="none"
          type="date"
          placeholder="请选择"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          style="width:150px"
        ></el-date-picker>
      </el-col>
      <el-col :span="2">
        <el-button @click="queryRepair()">查询</el-button>
      </el-col>
    </el-row>
    <el-row style="display: flex;align-items: center;">
      <el-col :span="2">
        <el-checkbox v-model="checkAllStatus" @change="changeCheck"
          >全选</el-checkbox
        >
      </el-col>
      <el-col :span="2">
        <el-button size="small" @click="BatchDelete">批量删除</el-button>
      </el-col>
    </el-row>
    <el-row>
      <el-table
        ref="multipleTable"
        @selection-change="handleSelectionChange"
        :row-style="{ color: '#303133' }"
        :header-cell-style="{
          backgroundColor: 'rgb(245, 247, 250)',
          color: '#606266'
        }"
        :data="tableData"
        border
        fit
        highlight-current-row
        style="width: 100%;margin-top: 10px;"
      >
        <el-table-column
          align="center"
          type="selection"
          width="55"
        ></el-table-column>
        <el-table-column prop="date" label="机号" width="80" align="center">
          <template slot-scope="scope">{{ scope.row.bed_number }}</template>
        </el-table-column>
        <el-table-column
          prop="name"
          label="保修时间"
          width="100"
          align="center"
        >
          <template slot-scope="scope">
            {{ getTime(scope.row.guarantee_date) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="出发时间"
          width="100"
          align="center"
        >
          <template slot-scope="scope">
            {{ getTimes(scope.row.start_time) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="到达时间"
          width="100"
          align="center"
        >
          <template slot-scope="scope">
            {{ getTimes(scope.row.arrive_time) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="完成时间"
          width="100"
          align="center"
        >
          <template slot-scope="scope">
            {{ getTimes(scope.row.finish_time) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="总路程(公里)"
          width="110"
          align="center"
        >
          <template slot-scope="scope">{{ scope.row.total_distance }}</template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="故障发生阶段"
          width="110"
          align="center"
        >
          <template slot-scope="scope">{{ scope.row.failure_stage }}</template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="故障提示信息及代码"
          width="120"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.code_information }}
          </template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="故障描述"
          width="100"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.fault_description }}
          </template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="原因分析"
          width="100"
          align="center"
        >
          <template slot-scope="scope">{{ scope.row.cause_analysis }}</template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="处理过程"
          width="100"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.treatment_process }}
          </template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="故障是否排除"
          width="110"
          align="center"
        >
          <template slot-scope="scope">{{ scope.row.exclude }}</template>
        </el-table-column>
        <el-table-column prop="address" label="原因" width="80" align="center">
          <template slot-scope="scope">{{ scope.row.reason }}</template>
        </el-table-column>
        <el-table-column label="操作" align="center" min-width="150px">
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="dark"
              content="编辑"
              placement="top"
            >
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit-outline"
                @click="
                  EditRepair(scope.row.id, scope.row.sampler, scope.$index)
                "
              ></el-button>
            </el-tooltip>

            <el-tooltip
              class="item"
              effect="dark"
              content="删除"
              placement="top"
            >
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="DeleteRepairs(scope.row.id, scope.$index)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="10"
        background
        style="margin-top:20px;float: right"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-row>

    <!-- 编辑维修记录 -->
    <el-dialog
      title="编辑维修记录"
      :visible.sync="dialogVisible"
      width="65%"
      center
    >
      <el-form :model="guaForm" ref="guaForm" :rules="repirRules">
        <el-row>
          <el-col :span="8">
            <el-form-item label="保修日期:" required prop="guarantee_date">
              <el-date-picker
                v-model="guaForm.guarantee_date"
                prefix-icon="none"
                type="date"
                placeholder="请选择"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                style="width:150px"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="出发时间:">
              <el-date-picker
                type="datetime"
                format="yyyy-MM-dd HH:mm"
                value-format="yyyy-MM-dd HH:mm"
                placeholder="选择时间"
                v-model="guaForm.start_time"
                style="width:200px;"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="到达时间:">
              <el-date-picker
                type="datetime"
                format="yyyy-MM-dd HH:mm"
                value-format="yyyy-MM-dd HH:mm"
                placeholder="选择时间"
                v-model="guaForm.arrive_time"
                style="width:200px;"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="完成时间:">
              <el-date-picker
                type="datetime"
                format="yyyy-MM-dd HH:mm"
                value-format="yyyy-MM-dd HH:mm"
                placeholder="选择时间"
                v-model="guaForm.finish_time"
                style="width:200px;"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总路程:(公里)">
              <el-input
                style="width:200px"
                v-model="guaForm.total_distance"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="故障发生阶段">
              <el-radio-group v-model="guaForm.failure_stage">
                <el-radio
                  :label="gender.id"
                  :value="gender.id"
                  v-for="(gender, index) in faultPhase"
                  :key="index"
                  >{{ gender.name }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="故障提示信息及代码">
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入内容"
                v-model="guaForm.code_information"
                style="width:500px"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="故障描述:" required prop="fault_description">
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入内容"
                v-model="guaForm.fault_description"
                style="width:300px"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="原因分析:">
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入内容"
                v-model="guaForm.cause_analysis"
                style="width:300px"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="处理过程:">
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入内容"
                v-model="guaForm.treatment_process"
                style="width:300px"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="上传图片:">
              <el-upload
                :data="uploadFileData"
                class="upload-demo"
                action="https://upload.qiniup.com"
                :on-success="handleSuccess"
                :before-upload="beforeUploadFile"
                :limit="1"
                ref="upload"
              >
                <el-button size="small" type="primary">上传图片</el-button>
              </el-upload>
            </el-form-item>
            <a class="el-upload-list__item-name">
              <i>
                <a @click="toLink()">{{ filename }}</a>
              </i>
            </a>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="故障是否排除:">
              <el-radio-group v-model="guaForm.exclude">
                <el-radio
                  :label="gender.id"
                  :value="gender.id"
                  v-for="(gender, index) in breakDown"
                  :key="index"
                  >{{ gender.name }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="原因:">
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入内容"
                v-model="guaForm.reason"
                style="width:300px"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="UpdateRepair('guaForm')"
          >保存</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAllSubregion,
  getAllRepair,
  EditRepair,
  UpdateRepair,
  DeleteRepair,
  queryRepair,
  DeleteRepairs
} from "@/api/manage";
import { uParseTime } from "@/utils/tools";
import { getFileExtension } from "@/utils/tools";
export default {
  name: "RepairForm",
  data() {
    return {
      dialogVisible: false,
      selectCulture: [],
      forms: {
        bed: "",
        sename: 1,
        start_time: "",
        end_time: ""
      },
      guaForm: {
        id: "",
        guarantee_date: "",
        start_time: "",
        arrive_time: "",
        finish_time: "",
        total_distance: "",
        failure_stage: "",
        fault_description: "",
        cause_analysis: "",
        treatment_process: "",
        images: "",
        exclude: "",
        reason: "",
        code_information: "",
        image_name: ""
      },
      isIndeterminate: false,
      checkAllStatus: false,
      bedNumber: [],
      tableData: [],
      qiniuDomain: "https://images.shengws.com/",
      uploadFileData: { token: "", key: "" },
      faultPhase: [
        { id: 1, name: "开机启动" },
        { id: 2, name: "自检" },
        { id: 3, name: "准备" },
        { id: 4, name: "治疗" },
        { id: 5, name: "消毒" }
      ],
      breakDown: [
        { id: 1, name: "是" },
        { id: 2, name: "待观察" },
        { id: 3, name: "未解决" }
      ],
      repirRules: {
        guarantee_date: [{ required: true, message: "请填写保修日期" }],
        fault_description: [{ required: true, message: "请填写故障描述" }]
      },
      filename: "",
      limit: 10,
      page: 1,
      total: 0,
      filename: ""
    };
  },
  methods: {
    changeCheck() {
      this.$refs.multipleTable.clearSelection();
      if (this.checkAllStatus) {
        this.$refs.multipleTable.toggleAllSelection();
      }
    },
    getAllSubregion() {
      getAllSubregion().then(response => {
        var zones = response.data.data.zones;
        var numbers = response.data.data.numbers;
        var number = [{ id: 0, number: "全部" }];
        for (let index = 0; index < numbers.length; index++) {
          const item = numbers[index];
          number.push({ id: item.id, number: item.number });
        }
        this.bedNumber = number;
      });
    },
    handleSelectionChange(val) {
      this.selectCulture = val;
    },
    getAllRepair() {
      getAllRepair(this.limit, this.page).then(response => {
        if (response.data.state === 1) {
          var repair = response.data.data.repair;
          console.log("repair是", repair);
          // eslint-disable-next-line no-unused-vars
          var total = response.data.data.total;
          this.total = total;
          for (let index = 0; index < repair.length; index++) {
            if (repair[index].failure_stage === 0) {
              repair[index].failure_stage = "";
            }

            if (repair[index].failure_stage === 1) {
              repair[index].failure_stage = "开机启动";
            }
            if (repair[index].failure_stage === 2) {
              repair[index].failure_stage = "自检";
            }
            if (repair[index].failure_stage === 3) {
              repair[index].failure_stage = "准备";
            }
            if (repair[index].failure_stage === 4) {
              repair[index].failure_stage = "治疗";
            }
            if (repair[index].failure_stage === 5) {
              repair[index].failure_stage = "消毒";
            }

            if (repair[index].exclude === 0) {
              repair[index].exclude = "";
            }

            if (repair[index].exclude === 1) {
              repair[index].exclude = "是";
            }
            if (repair[index].exclude === 2) {
              repair[index].exclude = "待观察";
            }
            if (repair[index].exclude === 3) {
              repair[index].exclude = "未解决";
            }
          }
          this.tableData = repair;
        }
      });
    },
    getTime(time) {
      return uParseTime(time, "{y}-{m}-{d}");
    },
    getTimes(time) {
      return uParseTime(time, "{y}-{m}-{d} {h}:{i}");
    },
    handleExceed(file) {
      // console.log(file)
    },
    handlePreview(file) {
      // console.log(file)
    },
    EditRepair(id) {
      this.dialogVisible = true;
      EditRepair(id).then(response => {
        if (response.data.state === 1) {
          var repair = response.data.data.repair;
          console.log("repair", repair);
          this.guaForm.guarantee_date = uParseTime(
            repair.guarantee_date,
            "{y}-{m}-{d}"
          );
          this.guaForm.start_time = uParseTime(
            repair.start_time,
            "{y}-{m}-{d} {h}:{i}"
          );
          this.guaForm.arrive_time = uParseTime(
            repair.arrive_time,
            "{y}-{m}-{d} {h}:{i}"
          );
          this.guaForm.finish_time = uParseTime(
            repair.finish_time,
            "{y}-{m}-{d} {h}:{i}"
          );
          this.guaForm.total_distance = repair.total_distance;
          this.guaForm.failure_stage = repair.failure_stage;
          this.guaForm.fault_description = repair.fault_description;
          this.guaForm.cause_analysis = repair.cause_analysis;
          this.guaForm.treatment_process = repair.treatment_process;
          this.guaForm.images = repair.images;
          this.guaForm.exclude = repair.exclude;
          this.guaForm.reason = repair.reason;
          this.guaForm.code_information = repair.code_information;
          this.guaForm.id = repair.id;
          this.filename = repair.image_name;
        }
      });
    },
    handleSuccess(res, file, fileList) {
      this.guaForm.images = this.qiniuDomain + res.url;
      console.log("图片上传", this.guaForm.images);
      this.$refs.upload.clearFiles();
      this.filename = file.name;
      this.guaForm.image_name = file.name;
    },
    beforeUploadFile(file) {
      this.filename = file.name;
      this.guaForm.image_name = file.name;
      const isLt2M = file.size / 1024 / 1024 <= 2048;
      console.log("filename", file);
      // console.log('视频大小', file.size / 1024 / 1024)
      // console.log('isLt2M是什么', isLt2M)

      if (!isLt2M) {
        this.$message.error("上传视频大小不能超过 2G!");
        return false;
      }
      var date = new Date();
      var ext = getFileExtension(file.name);
      var key =
        date.getFullYear() +
        (date.getMonth() + 1) +
        date.getDate() +
        date.getHours() +
        date.getMinutes() +
        date.getSeconds() +
        "_o_" +
        file.uid +
        "." +
        ext;
      const _self = this;
      return new Promise((resolve, reject) => {
        // eslint-disable-next-line no-undef
        getToken()
          .then(response => {
            const token = response.data.data.uptoken;
            console.log("token2是什么?", token);
            _self._data.uploadFileData.token = token;
            _self._data.uploadFileData.key = key;
            resolve(true);
          })
          // eslint-disable-next-line handle-callback-err
          .catch(err => {
            reject(false);
          });
      });
    },
    toLink() {
      window.location.href = this.guaForm.images;
    },
    UpdateRepair(formName) {
      this.$refs[formName].validate(valid => {
        this.guaForm.start_time = uParseTime(
          this.guaForm.start_time,
          "{y}-{m}-{d} {h}:{i}"
        );
        this.guaForm.arrive_time = uParseTime(
          this.guaForm.arrive_time,
          "{y}-{m}-{d} {h}:{i}"
        );
        this.guaForm.finish_time = uParseTime(
          this.guaForm.finish_time,
          "{y}-{m}-{d} {h}:{i}"
        );

        if (this.guaForm.failure_stage === "") {
          this.guaForm.failure_stage = 0;
        }

        var failurestages = this.guaForm.failure_stage;
        var falur = parseInt(failurestages);
        this.guaForm.failure_stage = falur;

        if (this.guaForm.exclude === "") {
          this.guaForm.exclude = 0;
        }
        var excludes = this.guaForm.exclude;
        var exclude = parseInt(excludes);
        this.guaForm.exclude = exclude;
        if (valid) {
          UpdateRepair(this.guaForm).then(response => {
            if (response.data.state === 1) {
              var repair = response.data.data.repair;
              this.dialogVisible = false;
              this.$message.success("修改成功");
            }
          });
        }
      });
    },
    BatchDelete() {
      if (this.selectCulture.length == 0) {
        this.$message.error("请选择要删除的信息");
        return false;
      }
      this.$confirm(
        "确认要删除所选记录吗? <br>删除后,信息将无法恢复",
        "删除提示",
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(() => {
        var ids = [];
        var idMap = {};
        for (const index in this.selectCulture) {
          ids.push(this.selectCulture[index].id);
          idMap[this.selectCulture[index].id] = this.selectCulture[index].id;
        }
        DeleteRepair({ ids: ids }).then(response => {
          if (response.data.state === 1) {
            var msg = response.data.data.msg;
            var planDataLength = this.tableData.length;
            for (let index = planDataLength - 1; index >= 0; index--) {
              if (this.tableData[index].id in idMap) {
                this.tableData.splice(index, 1);
              }
            }
            this.$message.success("删除成功");
          }
        });
      });
    },
    queryRepair() {
      queryRepair(
        this.forms.bed,
        this.forms.start_time,
        this.forms.end_time
      ).then(response => {
        if (response.data.state === 1) {
          var repair = response.data.data.repair;
          for (let index = 0; index < repair.length; index++) {
            if (repair[index].failure_stage === 0) {
              repair[index].failure_stage = "";
            }

            if (repair[index].failure_stage === 1) {
              repair[index].failure_stage = "开机启动";
            }
            if (repair[index].failure_stage === 2) {
              repair[index].failure_stage = "自检";
            }
            if (repair[index].failure_stage === 3) {
              repair[index].failure_stage = "准备";
            }
            if (repair[index].failure_stage === 4) {
              repair[index].failure_stage = "治疗";
            }
            if (repair[index].failure_stage === 5) {
              repair[index].failure_stage = "消毒";
            }

            if (repair[index].exclude === 0) {
              repair[index].exclude = "";
            }

            if (repair[index].exclude === 1) {
              repair[index].exclude = "是";
            }
            if (repair[index].exclude === 2) {
              repair[index].exclude = "待观察";
            }
            if (repair[index].exclude === 3) {
              repair[index].exclude = "未解决";
            }
          }
          this.tableData = repair;
        }
      });
    },
    handleSizeChange(limit) {
      this.limit = limit;
      this.getAllRepair();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.getAllRepair();
    },
    DeleteRepairs(id, index) {
      this.$confirm(
        "确认要删除所选记录吗? <br>删除后,信息将无法恢复",
        "删除提示",
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(() => {
        DeleteRepairs(id, index).then(response => {
          if (response.data.state === 1) {
            var msg = response.data.data.msg;
            this.tableData.splice(index, 1);
          }
        });
      });
    }
  },
  created() {
    this.getAllSubregion();
    this.getAllRepair();
  }
};
</script>

<style scoped>
.row {
  margin-bottom: 10px;
}
</style>
