<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="5" :xs="24">
        <category @selectCategory="selectCategory"></category>
      </el-col>
      <el-col :span="19" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true">
          <el-form-item label="物品名称" prop="assetName">
            <el-input v-model="queryParams.assetName"></el-input>
          </el-form-item>
          <el-form-item label="资产编号" prop="assetNumber">
            <el-input v-model="queryParams.assetName"></el-input>
          </el-form-item>
          <el-form-item label="资产类型" prop="assetType">
            <el-select
              v-model="queryParams.assetType"
              placeholder="资产类型"
              style="width: 170px">
              <el-option label="固定资产" value="0"/>
              <el-option label="耗材" value="1"/>
            </el-select>
          </el-form-item>
          <el-form-item label="资产状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="资产状态"
              style="width: 170px">
              <el-option label="在库" value="1"/>
              <el-option label="出库" value="2"/>
              <el-option label="出库(不回库)" value="3"/>
              <el-option label="报失" value="4"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" style="margin-bottom:8px">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['material:asset:add']"
            >新增入库
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['material:asset:export']"
            >导出
            </el-button>
          </el-col>
        </el-row>

        <el-table :data="assetList"
                  @row-click="rowClick"
                  size="mini">
          <el-table-column label="资产编号" prop="assetNumber"/>
          <el-table-column label="物品名称" prop="assetName" min-width="100" :show-overflow-tooltip="true"/>
          <el-table-column label="部门编号" prop="deptAssetNumber"/>
          <el-table-column label="资产类型" width="80">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.assetType==='1'" size="mini" type="warning">耗材</el-tag>
              <el-tag v-else size="mini" type="success">固定资产</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="设备型号" prop="equipmentType"/>
          <el-table-column label="设备编号" prop="equipmentNumber"/>
          <el-table-column label="原厂编号" prop="factoryNumber"/>
          <el-table-column label="生产厂家" prop="factoryName"/>
          <el-table-column label="购入日期" prop="buyDate"/>
          <el-table-column label="状态" width="80">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status==='1'" type="success" size="mini">在库</el-tag>
              <el-tag v-else-if="scope.row.status==='2'" size="mini">出库</el-tag>
              <el-tag v-else-if="scope.row.status==='3'" size="mini" type="info">出库(不回库)</el-tag>
              <el-tag v-else size="mini" type="warning">报失</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleTransfer(scope.row)"
                v-hasPermi="['material:asset:query']"
              >流转
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['material:asset:edit']"
              >修改
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['material:asset:delete']"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div style="margin-top: 10px;text-align: center">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryParams.pageNum"
            :page-sizes="[10, 20, 50]"
            :page-size="queryParams.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>
      </el-col>
    </el-row>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :close-on-click-modal="false">
      <el-row :gutter="20">
        <el-col :span="10">
          <el-form ref="form" :model="form" :rules="rules" size="mini" label-width="100px">
            <el-form-item label="所属分类" prop="categoryId">
              <el-cascader
                v-model="form.categoryId"
                :options="categoryOptions"
                :props="{ expandTrigger: 'hover',value:'id',label:'name',checkStrictly: true }"
                clearable></el-cascader>
            </el-form-item>
            <el-form-item label="物品名称" prop="assetName">
              <el-input v-model="form.assetName" placeholder="请输入资产名称" maxlength="30"/>
            </el-form-item>
            <el-form-item label="资产编号" prop="assetNumber">
              <el-input v-model="form.assetNumber" placeholder="请输入资产编号" maxlength="30"/>
            </el-form-item>
            <el-form-item label="部门编号" prop="deptAssetNumber">
              <el-input v-model="form.deptAssetNumber" placeholder="请输入资产编号" disabled/>
            </el-form-item>
            <el-form-item label="资产类型" prop="assetType">
              <el-radio-group v-model="form.assetType">
                <el-radio label="0">固定资产</el-radio>
                <el-radio label="1">耗材</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="设备设施名称" prop="equipmentName">
              <el-input v-model="form.equipmentName" placeholder="请输入设备设施名称" maxlength="30"/>
            </el-form-item>
            <el-form-item label="设备型号" prop="equipmentType">
              <el-input v-model="form.equipmentType" placeholder="请输入设备型号" maxlength="30"/>
            </el-form-item>
            <el-form-item label="设备编号" prop="equipmentNumber">
              <el-input v-model="form.equipmentNumber" placeholder="请输入设备编号" maxlength="30"/>
            </el-form-item>
            <el-form-item label="原厂编号" prop="factoryNumber">
              <el-input v-model="form.factoryNumber" placeholder="请输入原厂编号"></el-input>
            </el-form-item>
            <el-form-item label="生产厂家" prop="factoryName">
              <el-input v-model="form.factoryName" placeholder="请输入生产厂家"></el-input>
            </el-form-item>
            <el-form-item label="入库来源" prop="source">
              <el-select v-model="form.source">
                <el-option label="采购" value="1"></el-option>
                <el-option label="租赁" value="2"></el-option>
                <el-option label="借用" value="3"></el-option>
                <el-option label="赠送" value="4"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="购入日期" prop="buyDate">
              <el-date-picker
                v-model="form.buyDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
                style="width: 205px">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="定位位置" prop="location">
              <el-input v-model="form.location" placeholder="请输入定位位置"></el-input>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea"></el-input>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="14">
          <div class="accessory-header">
            <div class="a-h-title">
              配件信息
            </div>
            <el-button type="primary"
                       plain
                       icon="el-icon-plus"
                       size="mini"
                       @click="accessoryAdd"
            >添加配件
            </el-button>
          </div>

          <el-table :data="accessoryList" size="mini">
            <el-table-column label="配件名称">
              <template slot-scope="scope">
                <el-input v-model="scope.row.accessoryName" size="mini"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="配件编号">
              <template slot-scope="scope">
                <el-input v-model="scope.row.accessoryNumber" size="mini" disabled></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="accessoryDelete(scope.row)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="dialog-btn">
            <el-button type="primary" size="mini" @click="submitForm">确 定</el-button>
            <el-button size="mini" @click="cancel">取 消</el-button>
          </div>
        </el-col>
      </el-row>
    </el-dialog>

    <!-- 物品流转对话框 -->
    <el-dialog title="物品流转" :visible.sync="transferOpen" width="800px" append-to-body :close-on-click-modal="false">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form ref="transferForm" :model="transferForm" :rules="transferRules" size="mini" label-width="100px">
            <el-form-item label="物品名称" prop="assetName">
              <div>{{ transferForm.assetName }}</div>
            </el-form-item>
            <el-form-item label="资产编号" prop="assetNumber">
              <div>{{ transferForm.assetNumber }}</div>
            </el-form-item>
            <el-form-item label="部门编号" prop="deptAssetNumber">
              <div>{{ transferForm.deptAssetNumber }}</div>
            </el-form-item>
            <el-form-item label="设备型号" prop="equipmentType">
              <div>{{ transferForm.equipmentType }}</div>
            </el-form-item>
            <el-form-item label="物品说明" prop="remark">
              <div>{{ transferForm.remark }}</div>
            </el-form-item>

            <el-form-item label="选择配件" prop="accessoriesId">
              <el-select v-model="transferForm.accessoriesId" multiple>
                <el-option v-for="(item,index) in accessoryList" :label="item.accessoryName" :key="index"
                           :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="接收人" prop="receiveUserId">
              <el-cascader
                v-model="transferForm.receiveUserId"
                :options="userList"
                @change="(val)=>selectExecutor(val,'form')"
                :props="{ expandTrigger: 'hover',value:'id',label:'name' }"
                :show-all-levels="false"></el-cascader>
            </el-form-item>
            <el-form-item label="流转类型" prop="transferType">
              <el-select v-model="transferForm.transferType">
                <el-option v-for="item in transferTypeList" :label="item.dictLabel" :key="item.dictValue"
                           :value="item.dictValue"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="流转备注" prop="remark">
              <el-input v-model="transferForm.transferRemark" type="textarea"></el-input>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="12">
          <div style="font-size: 18px;margin-top: -15px">
            流转记录
          </div>
          <div style="height: 300px;margin-top: 10px">
            <el-timeline>
              <el-timeline-item
                v-for="(transfer, index) in assetTransferList"
                :key="index"
                :timestamp="transfer.transferDate" placement="top">
                <div>
                  <span>{{ getTransferTypeLabel(transfer.transferType) }}</span>
                  <span>({{ transfer.transferUserName }}</span>
                  <span><i class="el-icon-right"/></span>
                  <span>{{ transfer.receiveUserName }})</span>
                  <span>{{ '：' + transfer.transferRemark }}</span>
                </div>
              </el-timeline-item>
            </el-timeline>
          </div>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="submitTransferForm">确 定</el-button>
        <el-button size="mini" @click="cancelTransferForm">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 资产详情对话框 -->
    <el-dialog title="资产详情" :visible.sync="detailOpen" width="800px" append-to-body :close-on-click-modal="false">
      <asset-detail :form="form"></asset-detail>
    </el-dialog>

  </div>
</template>

<script>
import Category from "@/views/material/components/category";
import DeptUserTree from "@/components/DeptUserTree"
import AssetDetail from "./components/assetDetail"
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {getDeptAssetNumber, addAsset, listAsset, getAsset, updateAsset, delAsset,exportAsset} from "@/api/material/asset";
import {categoryTree} from "@/api/material/category";
import {getDeptUserTree} from "@/api/system/user";
import {getDictData} from "@/api/system/dict";
import {addTransfer, getTransferList} from "@/api/material/transfer";


export default {
  name: "asset",
  components: {Category, DeptUserTree, AssetDetail, Treeselect},
  data() {
    return {
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      assetList: [],
      form: {},
      accessoryList: [],
      title: '',
      open: false,
      categoryOptions: [],
      rules: {
        categoryId: [
          {required: true, message: "所属分类不能为空", trigger: "change"}
        ],
        assetName: [
          {required: true, message: "物品名称不能为空", trigger: "blur"}
        ],
        assetType: [
          {required: true, message: "资产类型不能为空", trigger: "change"}
        ],
        location: [
          {required: true, message: "定位位置不能为空", trigger: "blur"}
        ]
      },

      transferOpen: false,
      transferForm: {},
      assetTransferList: [],
      userList: [],
      transferTypeList: [],
      transferRules: {
        receiveUserId: [
          {required: true, message: "接收人不能为空", trigger: "change"}
        ],
        transferType: [
          {required: true, message: "流转类型不能为空", trigger: "change"}
        ]
      },
      detailOpen: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    selectCategory(data) {
      this.queryParams.categoryId = data;
      this.handleQuery();
    },
    getList() {
      listAsset(this.queryParams).then(res => {
        this.assetList = res.data.records;
        this.total = res.data.total;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        categoryId: undefined,
        assetName: undefined,
        assetNumber: undefined,
        deptAssetNumber: undefined,
        assetType: undefined,
        equipmentName: undefined,
        equipmentType: undefined,
        equipmentNumber: undefined,
        factoryNumber: undefined,
        factoryName: undefined,
        source: undefined,
        buyDate: undefined,
        location: undefined,
        remark: undefined
      };
      this.accessoryList = []
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.deptId = undefined;
      this.handleQuery();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getCategoryTree()
      getDeptAssetNumber().then(res => {
        this.form.deptAssetNumber = res.data
        this.open = true;
        this.title = "新增入库";
      });
    },
    handleExport() {
      exportAsset()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getCategoryTree()
      const id = row.id;
      getAsset(id).then(res => {
        this.form = res.data
        this.accessoryList = res.data.accessoryList || []
        this.open = true;
        this.title = "修改资产";
      })
    },
    getCategoryTree() {
      categoryTree().then(response => {
        this.categoryOptions = response.data;
      });
    },
    rowClick(row, column, event) {
      if (column.label === '操作') {
        return
      }
      getAsset(row.id).then(res => {
        this.form = res.data
        this.detailOpen = true;
      })
    },

    accessoryAdd() {
      let index = this.accessoryList.length + 1
      this.accessoryList.push(
        {accessoryName: '', accessoryNumber: this.form.deptAssetNumber + '-' + index}
      )
    },
    accessoryDelete(row) {
      this.accessoryList = this.accessoryList.filter(item => item.accessoryNumber != row.accessoryNumber)
      this.accessoryList.forEach((item, index) => {
        item.accessoryNumber = this.form.deptAssetNumber + '-' + (index + 1)
      })
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form['accessoryList'] = this.accessoryList
          if (this.form.id != undefined) {
            updateAsset(this.form).then(response => {
              this.$message.success("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.categoryId = this.form.categoryId[this.form.categoryId.length - 1]
            addAsset(this.form).then(response => {
              this.$message.success("入库成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除"' + row.assetName + '"？').then(function () {
        return delAsset(row.id);
      }).then(() => {
        this.getList();
        this.$message.success("删除成功");
      }).catch(() => {
      });
    },

    /**  流转按钮操作 */
    handleTransfer(row) {
      this.resetForm("transferForm");

      getDeptUserTree('').then(res => {
        this.userList = res.data
      })
      getDictData('transfer_type').then(res => {
        this.transferTypeList = res.data
      })
      getTransferList(row.id).then(res => {
        this.assetTransferList = res.data
      })
      getAsset(row.id).then(res => {
        this.transferForm = res.data
        this.transferForm.assetId = row.id
        this.accessoryList = res.data.accessoryList
        this.transferOpen = true
      })
    },
    getTransferTypeLabel(transferType) {
      if (this.transferTypeList.length === 0) {
        getDictData('transfer_type').then(res => {
          this.transferTypeList = res.data
        })
      }
      let typeLabel = ''
      this.transferTypeList.forEach(item => {
        if (item.dictValue == transferType) {
          typeLabel = item.dictLabel
        }
      })
      return typeLabel
    },
    submitTransferForm() {
      this.$refs["transferForm"].validate(valid => {
        if (valid) {
          console.log(this.transferForm);
          this.transferForm.id = undefined
          this.transferForm.accessoriesId = this.transferForm.accessoriesId.join()
          this.transferForm.receiveUserId = this.transferForm.receiveUserId[this.transferForm.receiveUserId.length - 1]
          addTransfer(this.transferForm).then(res => {
            this.$message.success("流转成功");
            this.transferOpen = false;
            this.getList();
          });
        }

      });
    },
    cancelTransferForm() {
      this.transferOpen = false
      this.transferForm = {}
      this.resetForm("transferForm");
    }

  }
}
</script>

<style scoped lang="scss">
.el-form-item--mini.el-form-item, .el-form-item--small.el-form-item {
  margin-bottom: 10px;
}

::v-deep.el-dialog__body {
  padding: 10px 20px 30px 20px;
}

.accessory-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;

  .a-h-title {
    font-size: 18px;
    margin-top: 7px;
  }
}

.dialog-btn {
  position: absolute;
  bottom: 0px;
  right: 20px;
}
</style>
