<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="title"
    width="1000px"
    @close="close"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="120px"
      label-position="left"
    >
      <el-form-item label="站点" prop="deviceCode">
        <el-select
          v-model="form.deviceCode"
          size="small"
          filterable
          placeholder="站点"
          @change="deviceChange"
        >
          <el-option
            v-for="item in devicesData"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('maintenance.bxsbsj')" prop="equipmentId">
        <el-select
          v-model="form.equipmentId"
          size="small"
          filterable
          placeholder="报修设备名称"
        >
          <el-option
            v-for="item in equipmentNameData"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('maintenance.bxlx')" prop="repairType">
        <el-select
          v-model="form.repairType"
          size="small"
          filterable
          placeholder="报修类型"
        >
          <el-option
            v-for="item in repairTypeData"
            :key="item.dataCode"
            :label="item.dataValue"
            :value="item.dataCode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="报修图片" prop="repairImg">
        <el-upload
          :action="fileUpdateUrl"
          :headers="{ token: token }"
          name="files"
          list-type="picture-card"
          :file-list="imageUrl"
          :on-success="handleAvatarSuccess"
          :on-remove="handleRemove"
          :before-upload="beforeAvatarUpload"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <!--        <div v-for="(item, index) in imageUrl" :key="index">-->
        <!--          <img-->
        <!--            v-if="item.filePath"-->
        <!--            :src="item.filePath"-->
        <!--            class="avatar"-->
        <!--            style="width: 100px; height: 100px"-->
        <!--          />-->
        <!--        </div>-->
        <!--        <el-upload-->
        <!--          class="avatar-uploader"-->
        <!--          :action="fileUpdateUrl"-->
        <!--          :headers="{ token: token }"-->
        <!--          :multiple="true"-->
        <!--          name="files"-->
        <!--          :show-file-list="false"-->
        <!--          :on-success="handleAvatarSuccess"-->
        <!--          :on-remove="handleRemove"-->
        <!--          :before-upload="beforeAvatarUpload"-->
        <!--        >-->
        <!--          <i class="el-icon-plus"></i>-->
        <!--        </el-upload>-->
        <!--        <div v-for="(item, index) in imageUrl" :key="index">-->
        <!--          <img-->
        <!--            v-if="item.filePath"-->
        <!--            :src="item.filePath"-->
        <!--            class="avatar"-->
        <!--            style="width: 100px; height: 100px"-->
        <!--          />-->
        <!--        </div>-->
      </el-form-item>
    </el-form>
    <div class="dialog-footer">
      <el-button size="small" @click="close">取 消</el-button>
      <el-button type="primary" size="small" @click="save">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { doAdd, doEdit, getDictData, getEquipments } from '@/api/repair';
import { getDevices } from '@/api/task';
import { baseURL } from '@/config';
import store from '@/store';
export default {
  data() {
    return {
      form: {
        id: '',
        deviceCode: '',
        equipmentId: '',
        repairType: '',
        repairImg: '',
      },
      rules: {
        deviceCode: [
          { required: true, trigger: 'change', message: '请选择站点' },
        ],
        equipmentId: [
          { required: true, trigger: 'change', message: '请选择保修设备名称' },
        ],
        repairType: [
          { required: true, trigger: 'blur', message: '请输入保修类型' },
        ],
        repairImg: [
          { required: true, trigger: 'blur', message: '请上传保修图片' },
        ],
      },
      filePath: baseURL + '/static/img/',
      projectId: '',
      fileUpdateUrl: '',
      clearable: true,
      title: '',
      token: '',
      imageUrl: [],
      dialogFormVisible: false,
      devicesData: [],
      equipmentNameData: [],
      repairTypeData: [],
      dialogVisible: false,
    };
  },
  created() {},
  methods: {
    showEdit(row) {
      this.imageUrl = [];
      if (!row) {
        this.title = '添加在线保修';
      } else {
        this.title = '编辑在线保修';
        const form = Object.assign({}, row);
        if (form.repairImg != null) {
          const imageUrl = form.repairImg.split(',');
          for (let i = 0; i < imageUrl.length; i++) {
            if (imageUrl[i]) {
              var url = this.filePath + imageUrl[i];
              this.imageUrl.push({ url });
            }
          }
          console.log(this.imageUrl);
        }
        this.form.id = form.id;
        this.form.deviceCode = form.device.code;
        this.getEquipmentsData();
        this.form.repairType = form.repairType.dataCode;
        this.form.repairImg = form.repairImg;
        this.form.equipmentId = form.equipment.id;
      }
      this.dialogFormVisible = true;
      this.projectId = sessionStorage.getItem('projectId');
      this.setUploadUrl();
      this.getDevicesData();
      this.getDictData();
    },
    deviceChange() {
      this.getEquipmentsData();
    },
    async getEquipmentsData() {
      const { data } = await getEquipments({
        deviceCode: this.form.deviceCode,
      });
      this.equipmentNameData = data;
    },
    async getDictData() {
      const { data } = await getDictData();
      this.repairTypeData = data.repairType;
    },
    async getDevicesData() {
      const { data } = await getDevices({ projectId: this.projectId });
      this.devicesData = data;
    },
    setUploadUrl() {
      this.token = store.getters['user/token'];
      this.fileUpdateUrl = baseURL + '/file/uploadImg';
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      const imageUrl = [];
      var repairImg = '';
      var filePath = this.filePath;
      fileList.forEach(function (item) {
        const url = item.url;
        imageUrl.push({ url });
        repairImg += url.substring(url.lastIndexOf('/') + 1) + ',';
      });
      this.imageUrl = imageUrl;
      this.form.repairImg = repairImg;
    },
    handleAvatarSuccess(res, file) {
      const imageUrl = this.imageUrl;
      const repairImg = this.form.repairImg;
      if (repairImg != '') {
        this.form.repairImg = repairImg + ',' + res.data;
      } else {
        this.form.repairImg = res.data;
      }
      const filePath = this.filePath + res.data;
      imageUrl.push({ filePath });
      this.imageUrl = imageUrl;
      // this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isLt2M;
    },
    close() {
      this.$refs['form'].resetFields();
      this.form = this.$options.data().form;
      this.dialogFormVisible = false;
      this.$emit('fetch-data');
    },
    save() {
      this.$refs['form'].validate(async valid => {
        if (valid) {
          if (this.form.id) {
            const { msg } = await doEdit(this.form);
            this.$notify({
              title: msg,
              type: 'success',
            });
          } else {
            delete this.form.id;
            const { msg } = await doAdd(this.form);
            this.$notify({
              title: msg,
              type: 'success',
            });
          }
          this.$refs['form'].resetFields();
          this.$parent.fetchData();
          this.dialogFormVisible = false;
        } else {
          return false;
        }
      });
    },
  },
};
</script>
<style lang="scss">
.el-dialog {
  .el-dialog__header {
    border-bottom: 1px solid #e3e3e3 !important;
    padding: 15px 20px;
  }
  .dialog-footer {
    text-align: right;
    .el button {
      height: 36px !important;
      min-height: 36px !important;
      line-height: 366px !important;
    }
  }
}
.avatar-uploader {
  //width: 100px;
  //height: 100px;
  //text-align: center;
  //border: 1px dashed #8c939d;
  .el-upload {
    line-height: 100px;
    display: flex;
  }
}
</style>
