<template>
    <div class="app-container">
        <!-- 头部区域 -->
        <el-row>
            <el-col class="item" :span="24">
                <span class="title">检索类型</span>
                <el-tag :type="currentType == null? '': 'info'" @click="getAssets(null, currentOrder, keyword)" style="cursor: pointer">
                    全部
                </el-tag>
                <el-tag class="tag" v-for="tag in tags" :key="tag.id" :type="currentType == tag.id? '': 'info'" @click="getAssets(tag.id, currentOrder, keyword)">
                    {{tag.name}}
                </el-tag>
            </el-col>
            <el-col class="item" :span="24">
                <span class="title">排序方式</span>
                <el-tag class="tag" :type="currentOrder == 0 || currentOrder == null? '': 'info'" @click="getAssets(currentType, 0, keyword)">
                    登记时间倒序
                </el-tag>
                <el-tag class="tag" :type="currentOrder == 1? '': 'info'" @click="getAssets(currentType, 1, keyword)">
                    登记时间顺序
                </el-tag>
            </el-col>
            <el-col class="item" :span="24">
                <span class="title">搜索名称</span>
                <el-input v-model="keyword" placeholder="输入名称检索" clearable style="width: 200px" @keyup.enter.native="getAssets(currentType, currentOrder, keyword)" size="small"></el-input>
                <el-button @click="getAssets(currentType, currentOrder, keyword)" size="small">搜索</el-button>
                <el-button type="primary" style="float: right" @click="openDialog1" size="small">登记资产</el-button>
            </el-col>
        </el-row>

        <!-- 列表区域 -->
        <el-table :data="assets" style="width: 100%" v-loading="loading">
            <el-table-column type="index" width="40"></el-table-column>
            <el-table-column label="资产图片" width="110">
                <template slot-scope="scope">
                    <el-image style="width: 100px; height: 100px" :src="'http://localhost:9102/img' + scope.row.pic"></el-image>
                </template>
            </el-table-column>
            <el-table-column prop="name" label="资产名称"></el-table-column>
            <el-table-column prop="modelNumber" label="型号" width="100"></el-table-column>
            <el-table-column prop="amount" label="数量" width="50">
                <template slot-scope="scope">{{assets2[scope.$index].amount}}{{scope.row.unit}}</template>
            </el-table-column>
            <el-table-column prop="tagName" label="分类" width="100">
                <template slot-scope="scope">{{assets2[scope.$index].tagName}}</template>
            </el-table-column>
            <el-table-column prop="address" label="位置" width="130"></el-table-column>
            <el-table-column prop="factory" label="生产厂家" width="130"></el-table-column>
            <el-table-column prop="serviceLife" label="服务期限" width="80"></el-table-column>
            <el-table-column prop="nextIndate" label="下次维护日期" width="110"></el-table-column>
            <el-table-column label="操作" width="180" fixed="right">
                <template slot-scope="scope">
                    <el-button type="primary" @click="toDetail(scope.row.id)">详情</el-button>
                    <el-button @click="openDialog3(scope.$index)">编辑</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 页码区域 -->
        <el-pagination
            v-if="total > 0"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageIndex"
            :page-sizes="[20, 50, 100]"
            :page-size="20"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            background
            style="float: right"
        ></el-pagination>

        <!-- 添加的dialog -->
        <el-dialog title="登记资产" :visible.sync="dialog1Visible" width="600px">
        <el-form ref="form1" :model="assetForm" :rules="rules1" label-width="110px">
            <el-form-item label="物品名称" prop="name">
            <el-input v-model="assetForm.name" placeholder="请输入物品名称" clearable></el-input>
            </el-form-item>
            <el-form-item label="型号" prop="modelNumber">
            <el-input v-model="assetForm.modelNumber" placeholder="请输入型号" clearable></el-input>
            </el-form-item>
            <el-row>
            <el-col :span="12">
                <el-form-item label="数量" prop="amount">
                <el-input v-model="assetForm.amount" placeholder="请输入数量" clearable></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="单位" prop="unit">
                <el-input v-model="assetForm.unit" placeholder="请输入单位" clearable></el-input>
                </el-form-item>
            </el-col>
            </el-row>
            <el-form-item label="物品图片" prop="image">
            <el-upload
                ref="upload"
                action="customize"
                :http-request="uploadDiscardFile"
                :limit="1"
                :before-remove="beforeRemove"
            >
                <!-- 这里添加和编辑的上传图片都没有检查类型 -->
                <!-- 并且所有的rules都没有详细调整触发方式以及数据类型限制 -->
                <el-button type="primary" :loading="loading">上传一张图片</el-button>
            </el-upload>
            </el-form-item>
            <el-form-item label="位置" prop="position">
            <el-input v-model="assetForm.position" placeholder="请输入位置" clearable></el-input>
            </el-form-item>
            <el-form-item label="生产厂家" prop="manufacturer">
            <el-input v-model="assetForm.manufacturer" placeholder="请输入生产厂家" clearable></el-input>
            </el-form-item>
            <el-form-item label="服务期限" prop="lifetime">
            <el-input v-model="assetForm.lifetime" placeholder="请输入服务期限" clearable></el-input>
            </el-form-item>
            <el-form-item label="下次维护日期" prop="nextDate">
            <el-date-picker
                v-model="assetForm.nextDate"
                type="date"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd"
                placeholder="请选择下次维护日期"
            ></el-date-picker>
            </el-form-item>
            <el-form-item label="所属分类" prop="belongTag">
            <el-tag
                class="tag"
                v-for="tag in tags"
                :key="tag.id"
                :type="assetForm.belongTag == tag.id? '': 'info'"
                @click="chooseTag(tag.id)"
                :closable="tag.id>7"
                @close="handleClose(tag.id)"
            >{{tag.name}}</el-tag>
            <!-- 添加和删除标签的地方 修改的话别忘了把下面那里也同步一下 -->
            <el-input
                class="input-new-tag"
                v-if="newTagVisible"
                v-model="newTagValue"
                ref="saveTagInput"
                size="small"
                style="width:80px"
                @keyup.enter.native="handleInputConfirm"
                @blur="newTagVisible=false"
            ></el-input>
            <el-button v-else class="button-new-tag" size="small" @click="showInput">新建分类</el-button>
            </el-form-item>
            <p class="tips">新增标签按回车键确认</p>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="dialog1Visible = false">取消</el-button>
            <el-button type="primary" @click="openDialog2">下一步</el-button>
        </span>
        </el-dialog>

        <!-- 编辑的dialog -->
        <el-dialog title="编辑资产" :visible.sync="dialog3Visible" width="600px">
        <el-form ref="form3" :model="assetForm" :rules="rules3" label-width="110px">
            <el-form-item label="物品名称" prop="name">
            <el-input v-model="assetForm.name" placeholder="请输入物品名称" clearable></el-input>
            </el-form-item>
            <el-form-item label="型号" prop="modelNumber">
            <el-input v-model="assetForm.modelNumber" placeholder="请输入型号" clearable></el-input>
            </el-form-item>
            <el-row>
            <el-col :span="12">
                <el-form-item label="单位" prop="unit">
                <el-input v-model="assetForm.unit" placeholder="请输入单位" clearable></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="物品图片" prop="image">
                <el-upload
                    ref="upload"
                    action="customize"
                    :http-request="uploadDiscardFile"
                    :limit="1"
                    :before-remove="beforeRemove"
                >
                    <el-button type="primary" :loading="loading">上传一张其他图片</el-button>
                </el-upload>
                </el-form-item>
            </el-col>
            </el-row>
            <el-form-item label="位置" prop="position">
            <el-input v-model="assetForm.position" placeholder="请输入位置" clearable></el-input>
            </el-form-item>
            <el-form-item label="生产厂家" prop="manufacturer">
            <el-input v-model="assetForm.manufacturer" placeholder="请输入生产厂家" clearable></el-input>
            </el-form-item>
            <el-form-item label="服务期限" prop="lifetime">
            <el-input v-model="assetForm.lifetime" placeholder="请输入服务期限" clearable></el-input>
            </el-form-item>
            <el-form-item label="下次维护日期" prop="nextDate">
            <el-date-picker
                v-model="assetForm.nextDate"
                type="date"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd"
                placeholder="请选择下次维护日期"
            ></el-date-picker>
            </el-form-item>
            <el-form-item label="所属分类" prop="belongTag">
            <el-tag
                class="tag"
                v-for="tag in tags"
                :key="tag.id"
                :type="assetForm.belongTag == tag.id? '': 'info'"
                @click="chooseTag(tag.id)"
                :closable="tag.id>7"
                @close="handleClose(tag.id)"
            >{{tag.name}}</el-tag>
            <!-- 添加和删除标签的地方 -->
            <el-input
                class="input-new-tag"
                v-if="newTagVisible"
                v-model="newTagValue"
                ref="saveTagInput"
                size="small"
                style="width:80px"
                @keyup.enter.native="handleInputConfirm"
                @blur="newTagVisible=false"
            ></el-input>
            <el-button v-else class="button-new-tag" size="small" @click="showInput">新建分类</el-button>
            </el-form-item>
            <p class="tips">新增标签按回车键确认 编号可以在详情中修改 图片不上传即默认为不修改</p>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="dialog3Visible = false">取消</el-button>
            <el-button type="primary" @click="editSubmit">更新</el-button>
        </span>
        </el-dialog>

        <!-- 添加的dialog -->
        <el-dialog title="分配资产编号" :visible.sync="dialog2Visible" width="600px">
        <el-form ref="form2" :model="assetForm2" :rules="rules2" label-width="110px">
            <el-form-item label="部门编号" prop="divisionCode">
            <el-input v-model="assetForm2.divisionCode" placeholder="请输入部门编号" clearable></el-input>
            </el-form-item>
            <el-form-item label="字母前缀" prop="suffix">
            <el-input v-model="assetForm2.suffix" placeholder="请输入字母前缀" clearable></el-input>
            </el-form-item>
            <p class="tips">编号构成：部门编号+字母前缀+四位数字（由系统自动生成）</p>
            <p class="tips">示例：ABCD-EFG0001</p>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="goBack">上一步</el-button>
            <el-button type="primary" @click="submit">提交</el-button>
        </span>
        </el-dialog>
    </div>
</template>

<script>
import request from "@/utils/request";
export default {
  data() {
    return {
      tags: [], //标签
      currentType: null, //当前标签
      currentOrder: 0, //当前排序方式
      assets: [], //资产
      assets2: [], //资产额外信息
      loading: false, //加载状态
      dialog1Visible: false, //添加的第一个dialog的状态
      dialog2Visible: false, //添加的第二个dialog的状态
      dialog3Visible: false, //编辑的dialog的状态
      newTagVisible: false, //新增种类的可见性
      newTagValue: "", //新增种类的名字
      keyword: "", //检索关键字
      assetForm: {
        id: null,
        name: "",
        modelNumber: "",
        amount: "",
        unit: "",
        image: null,
        position: "",
        manufacturer: "",
        lifetime: "",
        nextDate: "",
        belongTag: null
      }, //dialog1中的表单
      assetForm2: {
        divisionCode: "",
        suffix: ""
      }, //dialog2中的表单
      rules1: {
        name: [{ required: true, message: "请输入名字", trigger: "blur" }],
        modelNumber: [
          { required: true, message: "请输入编号", trigger: "blur" }
        ],
        amount: [{ required: true, message: "请输入数量", trigger: "blur" }],
        unit: [{ required: true, message: "请输入单位", trigger: "blur" }],
        position: [{ required: true, message: "请输入地点", trigger: "blur" }],
        manufacturer: [
          { required: true, message: "请输入生产商", trigger: "blur" }
        ],
        lifetime: [
          { required: true, message: "请输入使用时间", trigger: "blur" }
        ],
        nextDate: [
          { required: true, message: "请输入下次维护时间", trigger: "blur" }
        ],
        belongTag: [{ required: true, message: "请选择标签", trigger: "blur" }]
      }, //验证规则1
      rules2: {
        divisionCode: [
          { required: true, message: "请输入部门编码", trigger: "blur" }
        ],
        suffix: [{ required: true, message: "请输入前缀编码", trigger: "blur" }]
      }, //验证规则2
      rules3: {
        name: [{ required: true, message: "请输入名字", trigger: "blur" }],
        modelNumber: [
          { required: true, message: "请输入编号", trigger: "blur" }
        ],
        unit: [{ required: true, message: "请输入单位", trigger: "blur" }],
        position: [{ required: true, message: "请输入地点", trigger: "blur" }],
        manufacturer: [
          { required: true, message: "请输入生产商", trigger: "blur" }
        ],
        lifetime: [
          { required: true, message: "请输入使用时间", trigger: "blur" }
        ],
        nextDate: [
          { required: true, message: "请输入下次维护时间", trigger: "blur" }
        ],
        belongTag: [{ required: true, message: "请选择标签", trigger: "blur" }]
      }, //验证规则3
      //分页相关
      pageIndex: 1,
      pageSize: 20,
      total: 0
    };
  },
  methods: {
    //页码规格变更
    handleSizeChange(val) {
      this.pageSize = val;
      //重新获取
      this.getAssets(this.currentType, this.currentOrder, this.keyword);
    },

    //页码页数变更
    handleCurrentChange(val) {
      this.pageIndex = val;
      //重新获取
      this.getAssets(this.currentType, this.currentOrder, this.keyword);
    },

    //到详情页面
    toDetail(id) {
      if (id != null) {
        this.$router.push("/detail/" + id);
      } else {
        this.$message({
          message: "发生错误",
          type: "error"
        });
      }
    },

    //打开dialog1新建第一部分
    openDialog1() {
      this.assetForm.id = null;
      this.assetForm.name = "";
      this.assetForm.modelNumber = "";
      this.assetForm.amount = "";
      this.assetForm.unit = "";
      this.assetForm.image = null;
      this.assetForm.position = "";
      this.assetForm.manufacturer = "";
      this.assetForm.lifetime = "";
      this.assetForm.nextDate = "";
      this.assetForm.belongTag = null;
      this.dialog1Visible = true;
    },

    //打开dialog3编辑
    openDialog3(index) {
      this.assetForm.id = this.assets[index].id;
      this.assetForm.name = this.assets[index].name;
      this.assetForm.modelNumber = this.assets[index].modelNumber;
      this.assetForm.unit = this.assets[index].unit;
      this.assetForm.image = null;
      this.assetForm.position = this.assets[index].address;
      this.assetForm.manufacturer = this.assets[index].factory;
      this.assetForm.lifetime = this.assets[index].serviceLife;
      this.assetForm.nextDate = this.assets[index].nextIndate;
      this.assetForm.belongTag = this.assets[index].tagId;
      this.dialog3Visible = true;
    },

    //打开dialog2新建第二部分
    openDialog2() {
      this.$refs.form1.validate(valid => {
        if (!valid) {
          return;
        } else if (this.assetForm.belongTag == null) {
          this.$message({
            message: "尚未选择种类",
            type: "error"
          });
        } else if (this.assetForm.image == null) {
          this.$message({
            message: "尚未上传图片",
            type: "error"
          });
        } else {
          this.dialog1Visible = false;
          this.dialog2Visible = true;
          this.assetForm2.divisionCode = "";
          this.assetForm2.suffix = "";
        }
      });
    },

    //dialog2时返回上一步
    goBack() {
      this.dialog2Visible = false;
      this.dialog1Visible = true;
    },

    //新建提交
    submit() {
      this.$refs.form2.validate(valid => {
        if (valid) {
          this.loading = true;
          var form = new FormData();
          form.append("name", this.assetForm.name);
          form.append("modelNumber", this.assetForm.modelNumber);
          form.append("amount", this.assetForm.amount);
          form.append("unit", this.assetForm.unit);
          form.append("address", this.assetForm.position);
          form.append("factory", this.assetForm.manufacturer);
          form.append("serviceLife", this.assetForm.lifetime);
          form.append("nextIndate", this.assetForm.nextDate);
          form.append("tagId", this.assetForm.belongTag);
          form.append("divisionCode", this.assetForm2.divisionCode);
          form.append("suffix", this.assetForm2.suffix);
          form.append("multipartFile", this.assetForm.image); //添加照片
          request({
            url: "/goods/insertAssets",
            method: "post",
            data: form
          })
            .then(response => {
              //清除文件并获取信息
              this.$refs.upload.clearFiles();
              this.getTags();
              this.getAssets(null, null, null);
              this.dialog2Visible = false;
              this.loading = false;
              this.$message({
                message: "添加成功",
                type: "success"
              });
            })
            .catch(error => {
              this.loading = false;
            });
        }
      });
    },

    //编辑提交
    editSubmit() {
      this.$refs.form3.validate(valid => {
        if (valid) {
          this.loading = true;
          var form = new FormData();
          form.append("id", this.assetForm.id);
          form.append("name", this.assetForm.name);
          form.append("modelNumber", this.assetForm.modelNumber);
          form.append("unit", this.assetForm.unit);
          form.append("address", this.assetForm.position);
          form.append("factory", this.assetForm.manufacturer);
          form.append("serviceLife", this.assetForm.lifetime);
          form.append("nextIndate", this.assetForm.nextDate);
          form.append("tagId", this.assetForm.belongTag);
          form.append("multipartFile", this.assetForm.image); //添加照片
          request({
            url: "/goods/updateAsset",
            method: "post",
            data: form
          })
            .then(response => {
              //清除文件并获取信息
              this.$refs.upload.clearFiles();
              this.getTags();
              this.getAssets(null, null, null);
              this.dialog3Visible = false;
              this.loading = false;
              this.$message({
                message: "编辑成功",
                type: "success"
              });
            })
            .catch(error => {
              this.loading = false;
            });
        }
      });
    },

    //获取标签列表
    getTags() {
      request({
        url: "/goods-tags/getTags",
        method: "post"
      })
        .then(response => {
          this.tags = response.data;
        })
        .catch(error => {});
    },

    //分页获取资产列表
    getAssets(type, order, keyword) {
      this.currentType = type;
      this.currentOrder = order;
      this.loading = true;
      request({
        url: "/goods/getAssetsByPage",
        method: "post",
        params: {
          pageIndex: this.pageIndex,
          pageSize: this.pageSize,
          type: type,
          order: order,
          name: keyword
        }
      })
        .then(response => {
          this.assets = response.data.page.records;
          this.assets2 = response.data.additional;
          this.total = response.data.page.total;
          this.loading = false;
        })
        .catch(error => {
          this.loading = false;
        });
    },

    //获取上传的文件
    uploadDiscardFile(params) {
      this.assetForm.image = params.file;
      return false;
    },

    //文件上传的移除操作
    beforeRemove() {
      this.assetForm.image = null;
    },

    //表单内选择标签
    chooseTag(id) {
      this.assetForm.belongTag = id;
    },

    //点击删除标签
    handleClose(id) {
      this.$confirm("确定要删除分类吗", "删除分类", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          request({
            url: "/goods-tags/deleteTags",
            method: "post",
            params: { id: id }
          })
            .then(response => {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              //这里要清除选中的和表单中的tag
              this.currentType = null;
              this.assetForm.belongTag = null;
              this.getTags();
            })
            .catch(error => {});
        })
        .catch(() => {});
    },

    //点击开始新增标签
    showInput() {
      this.newTagVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    //确认新增标签
    handleInputConfirm() {
      if (this.newTagValue != "") {
        this.$confirm(
          "确定要添加新分类" + this.newTagValue + "吗",
          "添加标签",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "info"
          }
        )
          .then(() => {
            request({
              url: "/goods-tags/insertTags",
              method: "post",
              params: { name: this.newTagValue }
            })
              .then(response => {
                this.$message({
                  type: "success",
                  message: "添加成功!"
                });
                this.getTags();
                this.newTagVisible = false;
                this.newTagValue = "";
              })
              .catch(error => {
                this.newTagVisible = false;
                this.newTagValue = "";
              });
          })
          .catch(() => {
            this.newTagVisible = false;
            this.newTagValue = "";
          });
      }
    }
  },
  mounted() {
    this.getTags();
    this.getAssets(null, null, null);
  }
};
</script>

<style scoped>
.title {
  line-height: 32px;
  font-size: 14px;
}
.tag {
  margin-right: 5px;
  margin-bottom: 5px;
  cursor: pointer;
}
.item {
  margin-bottom: 5px;
}
.tips {
  width: 100%;
  text-align: center;
  font-size: 12px;
  color: #777;
}
</style>

