<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="5" :xs="24">
        <category ref="cgTreee" @selectCategory="selectCategory"></category>
      </el-col>
      <el-col :span="19" :xs="24">
        <div class="query-container">
          <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true">
            <el-form-item label="是否配件" prop="accessoryFlag">
              <el-switch v-model="queryParams.accessoryFlag"
                         active-value="1"
                         inactive-value="0">
              </el-switch>
            </el-form-item>
            <el-form-item prop="assetName">
              <el-input v-model="queryParams.assetName" placeholder="物品名称" clearable></el-input>
            </el-form-item>
            <el-form-item prop="assetType">
              <el-select
                v-model="queryParams.assetType"
                placeholder="资产类型"
                clearable
                style="width: 100px">
                <el-option
                  v-for="dict in dict.type.asset_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item prop="status">
              <el-select
                v-model="queryParams.status"
                placeholder="资产状态"
                clearable
                style="width: 120px">
                <el-option
                  v-for="dict in dict.type.asset_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"/>
              </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>
        </div>

        <el-table :data="assetList"
                  @row-click="rowClick"
                  stripe
                  height="calc(100vh - 180px)"
                  size="mini">
          <el-table-column label="唯一编码" prop="deptAssetNumber" :show-overflow-tooltip="true"/>
          <el-table-column label="物品名称" prop="assetName" min-width="100" :show-overflow-tooltip="true"/>
          <!--          <el-table-column label="公司资产编号" prop="assetNumber" :show-overflow-tooltip="true"/>-->
          <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" :show-overflow-tooltip="true"/>
          <!--          <el-table-column label="设备编号" prop="equipmentNumber" :show-overflow-tooltip="true"/>-->
          <!--          <el-table-column label="原厂编号" prop="factoryNumber" :show-overflow-tooltip="true"/>-->
          <el-table-column label="生产厂家" prop="factoryName" :show-overflow-tooltip="true"/>
          <el-table-column label="购入日期" prop="buyDate"/>
          <el-table-column label="库存数量" prop="num"/>
          <el-table-column label="状态" width="90">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status==='1'" type="success">在库</el-tag>
              <el-tag v-else-if="scope.row.status==='2'">出库</el-tag>
              <el-tag v-else-if="scope.row.status==='3'" type="info">出库(不回库)</el-tag>
              <el-tag v-else-if="scope.row.status==='4'" type="warning">报失</el-tag>
              <el-tag v-else type="danger">丢弃</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="定位位置" prop="location" width="80"/>
          <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" class="asset-dialog" width="800px" append-to-body>
      <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" disabled/>
            </el-form-item>
            <el-form-item label="资产类型" prop="assetType">
              <el-radio-group v-model="form.assetType">
                <el-radio
                  v-for="dict in dict.type.asset_type"
                  :key="dict.value"
                  :label="dict.value">{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="数量" prop="num" v-if="form.assetType==='1'">
              <el-input-number v-model="form.num" :min="1"></el-input-number>
            </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
                  v-for="dict in dict.type.s_source"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"/>
              </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="选择日期"
                :picker-options="pickerOptions"
                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" class="asset-dialog" width="800px" append-to-body
               @close="cancelTransferForm">
      <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="location">
              <div>{{ transferForm.location }}</div>
            </el-form-item>
            <el-form-item v-if="transferForm.assetType==='1'" label="库存数">
              <div>{{ transferForm.num }}</div>
            </el-form-item>
            <el-form-item label="流转数量" prop="receiveNum" v-if="transferForm.assetType==='1'">
              <el-input-number v-model="transferForm.receiveNum" :max="transferForm.num"></el-input-number>
              <el-tooltip class="item" effect="dark" content="不填表示领取剩余全部库存" placement="right">
                <div style="margin-left: 10px" class="el-icon-info"></div>
              </el-tooltip>
            </el-form-item>
            <el-form-item label="选择配件" prop="accessoriesId">
              <el-select v-model="transferForm.accessoriesId" multiple style="width: 200px">
                <el-option v-for="(item,index) in accessoryList" :label="item.accessoryName" :key="index"
                           :value="item.id">
                  <span style="float: left">{{ item.accessoryName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 10px">{{ item.location }}</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="接收人" prop="receiveUserId">
              <dept-user-tree ref="dut" :userList="userList" style="width: 200px"
                              @selected="selectReceiveUserId"></dept-user-tree>
            </el-form-item>
            <el-form-item label="流转类型" prop="transferType">
              <el-select v-model="transferForm.transferType" style="width: 200px">
                <el-option
                  v-for="dict in dict.type.transfer_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="流转备注" prop="transferRemark">
              <el-input v-model="transferForm.transferRemark" type="textarea"
                        :autosize="{ minRows: 4, maxRows: 7}"></el-input>
            </el-form-item>
          </el-form>
          <div class="transfer-btn">
            <el-button type="primary" size="mini" @click="submitTransferForm">确 定</el-button>
            <el-button size="mini" @click="cancelTransferForm">取 消</el-button>
          </div>
        </el-col>
        <el-col :span="12">
          <div style="margin-top: -15px">
            <span style="font-size: 18px;margin-right: 10px">流转记录</span>
            <span style="font-size: 12px"><i class="el-icon-info"/>红点表示接收人还未确认</span>
          </div>
          <div style="height: 500px;margin-top: 10px;overflow: auto">
            <el-timeline :reverse="true">
              <el-timeline-item
                v-for="(transfer, index) in assetTransferList"
                :key="index"
                :timestamp="transfer.transferDate" placement="top">
                <div style="font-size: 12px;color: #1c84c6">
                  <span>{{ getTransferTypeLabel(transfer.transferType) }}</span>
                  <span>({{ transfer.transferUserName }}</span>
                  <span><i class="el-icon-right"/></span>
                  <span>{{ transfer.receiveUserName }}</span>
                  <el-badge v-if="transfer.receiveConfirm!='1'" is-dot></el-badge>
                  <span>)</span>
                  <span>{{ '：' + transfer.transferRemark }}</span>
                </div>
                <div style="margin-top: 5px" v-if="transfer.accessoryList.length>0">
                  <span style="font-size: 10px">配件:</span>
                  <template v-for="(item,index) in transfer.accessoryList">
                    <el-tooltip :content="item.deptAssetNumber" placement="top">
                      <el-tag size="mini" style="margin-left: 5px">{{ item.assetName }}</el-tag>
                    </el-tooltip>
                  </template>
                </div>
              </el-timeline-item>
            </el-timeline>
          </div>
        </el-col>
      </el-row>
    </el-dialog>

    <!-- 资产详情对话框 -->
    <el-dialog title="资产详情" :visible.sync="detailOpen" class="asset-dialog" width="800px" append-to-body>
      <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";
import DateUtil from "@/utils/date";


export default {
  name: "asset",
  components: {Category, DeptUserTree, AssetDetail, Treeselect},
  dicts: ['asset_type', 'asset_status', 's_source', 'transfer_type'],
  data() {
    return {
      selectCategoryId: undefined,
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      assetList: [],
      form: {
        num: 1
      },
      accessoryList: [],
      title: '',
      open: false,
      categoryOptions: [],
      rules: {
        categoryId: [
          {required: true, message: "所属分类不能为空", trigger: "change"}
        ],
        assetName: [
          {required: true, message: "物品名称不能为空", trigger: "blur"}
        ],
        assetType: [
          {required: true, message: "资产类型不能为空", trigger: "change"}
        ],
        num: [
          {required: true, message: "数量不能为空", trigger: "change"}
        ],
        source: [
          {required: true, message: "入库来源不能为空", trigger: "change"}
        ],
        location: [
          {required: true, message: "定位位置不能为空", trigger: "blur"}
        ]
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > DateUtil.unix(DateUtil.day()) * 1000
        }
      },

      transferOpen: false,
      transferForm: {},
      assetTransferList: [],
      userList: [],
      transferRules: {
        receiveUserId: [
          {required: true, message: "接收人不能为空", trigger: "change"}
        ],
        transferType: [
          {required: true, message: "流转类型不能为空", trigger: "change"}
        ],
        transferRemark: [
          {required: true, message: "流转备注不能为空", trigger: "blur"}
        ]
      },
      detailOpen: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    selectCategory(data) {
      this.selectCategoryId = 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,
        num: 1,
        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;
      if (this.selectCategoryId) {
        this.queryParams.categoryId = this.selectCategoryId
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.deptId = undefined;
      this.$refs.cgTreee.clear()
      this.handleQuery();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getCategoryTree()
      getDeptAssetNumber().then(res => {
        this.form.deptAssetNumber = res.data
        if (this.selectCategoryId) {
          this.form.categoryId = this.selectCategoryId
        }
        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() {
      if (this.accessoryList && this.accessoryList.length > 0) {
        let valid = true
        this.accessoryList.forEach(item => {
          if (!item.accessoryName) {
            valid = false
          }
        })
        if (!valid) {
          this.$message.warning("配件名称不能为空")
          return
        }
      }
      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 {
            if (typeof this.form.categoryId != 'string') {
              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) {
      getDeptUserTree('1').then(res => {
        this.userList = 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) {
      let typeLabel = ''
      this.dict.type.transfer_type.forEach(item => {
        if (item.value === transferType) {
          typeLabel = item.label
        }
      })
      return typeLabel
    },
    selectReceiveUserId(val) {
      this.$set(this.transferForm, 'receiveUserId', val)
    },

    submitTransferForm() {
      this.$refs["transferForm"].validate(valid => {
        if (valid) {
          this.transferForm.id = undefined
          if (this.transferForm.accessoriesId) {
            this.transferForm.accessoriesId = this.transferForm.accessoriesId.join()
          }
          addTransfer(this.transferForm).then(res => {
            this.$message.success("流转成功");
            this.$refs.dut.clearText();
            this.transferOpen = false;
            this.resetForm("transferForm");
            this.getList();
          });
        }
      });
    },
    cancelTransferForm() {
      this.$refs.dut.clearText();
      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;
}

.asset-dialog ::v-deep .el-dialog__body {
  padding: 0 20px 10px 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;
}

.transfer-btn {
  text-align: right;
  margin-top: 20px;
}
</style>
