<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" class="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单据编号" prop="orderNumber">
        <el-input
          v-model="queryParams.orderNumber"
          placeholder="请输入单据编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="盘点部门" prop="inventoryDepartment">
        <treeselect
            v-model="queryParams.inventoryDepartment"
            :options="deptOptions"
            placeholder="选择盘点部门"
            @keyup.enter.native="handleQuery"
          />
      </el-form-item>
      <el-form-item label="盘点地点" prop="inventoryLocation">
        <treeselect v-model="queryParams.inventoryLocation" :options="locationOption" :normalizer="tenantIdnormalizer" placeholder="选择位置" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="盘点人" prop="inventoryBy">
        <el-input
          v-model="queryParams.inventoryBy"
          placeholder="请输入盘点人"
          clearable
          @keyup.enter.native="handleQuery"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="盘点日期" prop="inventoryDate">
        <el-date-picker clearable
          v-model="queryParams.inventoryDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择盘点日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="盘点状态" prop="inventoryStatus">
        <el-select v-model="queryParams.inventoryStatus" placeholder="请选择盘点状态 " clearable>
          <el-option
            v-for="dict in dict.type.inventory_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="盘点结果 " prop="inventoryResult">
        <el-select v-model="queryParams.inventoryResult" placeholder="请选择盘点结果 " clearable>
          <el-option
            v-for="dict in dict.type.inventory_result"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="记录状态 " prop="recordStatus">
        <el-select v-model="queryParams.recordStatus" placeholder="请选择记录状态 " clearable>
          <el-option
            v-for="dict in dict.type.asset_record_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" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['inventory:inventory:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['inventory:inventory:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['inventory:inventory:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['inventory:inventory:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="onOpenExportDetail"
          v-hasPermi="['inventory:inventory:export']"
        >导出报表</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-download"
          size="mini"
          @click="onOpenLoss"
          v-hasPermi="['inventory:inventory:export']"
        >资产报表</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="elTable" v-loading="loading" :data="inventoryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="单据编号" align="center" prop="orderNumber" width="100">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="查看明细" placement="left">
            <div class="clickNumber" @click="onOpenDetail(scope.row.orderNumber)">{{scope.row.orderNumber}}</div>
          </el-tooltip>
          <!-- <router-link :to="`/inventory/inventory/detail/${scope.row.orderNumber}`" class="link-type">
            <span>{{ scope.row.orderNumber }}</span>
          </router-link> -->
        </template>
      </el-table-column>
      <el-table-column label="任务名称" align="center" prop="name" width="190"/>
      <el-table-column label="二维码" align="center" prop="orderNumber" width="90">
        <template slot-scope="scope">
          <image-preview :src="getCode(scope.row.orderNumber)" :width="80" :height="80" />
        </template>
      </el-table-column>
      <el-table-column label="盘点部门" align="center" prop="inventoryDepartmentName" />
      <el-table-column label="盘点位置" align="center" prop="inventoryLocationName" width="200">
      </el-table-column>
      <el-table-column label="盘点人" align="center" prop="inventoryBy" />
      <el-table-column label="盘点日期" align="center" prop="inventoryDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.inventoryDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="盘点状态 " align="center" prop="inventoryStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.inventory_status" :value="scope.row.inventoryStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="盘点结果 " align="center" prop="inventoryResult">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.inventory_result" :value="scope.row.inventoryResult"/>
        </template>
      </el-table-column>
      <el-table-column label="记录状态 " align="center" prop="recordStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.asset_record_status" :value="scope.row.recordStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="记录创建时间" align="center" prop="createdTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            :disabled="scope.row.inventoryStatus > 1"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['inventory:inventory:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['inventory:inventory:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改资产盘点记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="单据编号" prop="orderNumber">
          <el-input v-model="form.orderNumber" placeholder="请输入单据编号" />
        </el-form-item> -->
        <el-form-item label="任务名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="盘点部门" prop="inventoryDepartment">
          <treeselect
            v-model="form.inventoryDepartment"
            :options="deptOptions"
            placeholder="选择盘点部门"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="盘点人" prop="inventoryBy">
          <el-input v-model="form.inventoryBy" placeholder="请输入盘点人" >
            <el-button slot="append" icon="el-icon-search" @click="openUserSearch = true"></el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="盘点日期" prop="inventoryDate">
          <el-date-picker clearable
            v-model="form.inventoryDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择盘点日期"
            :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="盘点位置" prop="inventoryLocation">
          <treeselect
          v-model="form.inventoryLocation" 
          :multiple="true"
          :clearable="true"
          :searchable="true"
          :open-on-click="true"
          :clear-on-select="true"
          :sort-value-by="'INDEX'"
          :options="locationOption"
          :limit="3" 
          placeholder="选择位置" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="warning"
          @click="submitForm(1)"
          >提 交</el-button
        >
        <el-button type="primary" @click="submitForm(0)">{{form.recordStatus === 1 ? '撤 回' : '保 存'}}</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="openUserSearch">
      <UserSearch @submit="onSelectUser" @cancel="() => {openUserSearch = false}" v-if="openUserSearch"></UserSearch>
    </el-dialog>

    <el-dialog :visible.sync="openLoss" title="资产报表查看">
      <el-row>
        <el-form>
          <el-form-item label="盘点部门" prop="inventoryDepartment">
            <treeselect
              v-model="deptId"
              :options="deptOptions"
              placeholder="选择盘点部门"
              @keyup.enter.native="onQueryLoss"
            />
          </el-form-item>
        </el-form>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="onQueryLoss">搜索</el-button>
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="onLossExport"
          v-hasPermi="['inventory:inventory:export']"
        >导出</el-button>
      </el-row>
      <el-row>
        <el-table :data="lossData">
          <el-table-column
            prop="totalLossVal"
            label="损耗总额"
            width="100">
          </el-table-column>
          <el-table-column
            prop="date"
            label="盘点时间"
            width="100">
          </el-table-column>
          <el-table-column label="资产盘点结果集">
            <el-table-column
              prop="date"
              label="盘点时间"
              width="100">
            </el-table-column>
          </el-table-column>
        </el-table>
      </el-row>
    </el-dialog>

    <el-dialog title="导出报表" :visible.sync="openExport" width="360px">
      <el-form ref="form" :model="exportParams" label-width="80px">
        <el-form-item label="盘点部门" prop="inventoryDepartment">
          <treeselect
              v-model="exportParams.inventoryDepartment"
              :options="deptOptions"
              placeholder="选择盘点部门"
              @keyup.enter.native="handleQuery"
            />
        </el-form-item>
        <el-form-item label="盘点地点" prop="inventoryLocation">
          <treeselect v-model="exportParams.inventoryLocation" :options="locationOption" :normalizer="tenantIdnormalizer" placeholder="选择位置" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="盘点日期" prop="inventoryDate">
          <el-date-picker clearable
            v-model="exportParams.inventoryDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择盘点日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitExport">确 定</el-button>
        <el-button @click="openExport=false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { deptTreeSelect } from '@/api/system/user.js'
import { listInventory, getInventory, delInventory, addInventory, updateInventory,selectQrCode,getDepAssetLossTb } from "@/api/inventory/inventory";
import { treeSelect } from "@/api/asset/location";
import { listDept } from "@/api/system/dept";
import UserSearch from '@/components/SysUserSearch/index.vue'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "Inventory",
  dicts: ['inventory_result', 'asset_record_status', 'inventory_status'],
  components : {
    UserSearch,
    Treeselect
  },
  data() {
    return {
      openUserSearch: false,
      // 盘点单号
      inventoryNumber: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 资产盘点记录表格数据
      inventoryList: [],
      locationOption: [],
      // 部门树选项
      deptOptions: [],
      arr: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNumber: null,
        name: null,
        inventoryDepartment: null,
        inventoryBy: null,
        inventoryDate: null,
        inventoryLocation: null,
        inventoryStatus: null,
        inventoryResult: null,
        recordStatus: null,
      },
      openExport: false,
      exportParams: {
        inventoryDepartment: null,
        inventoryDate: null,
        inventoryLocation: null,
        recordStatus: 1,
      },
      openLoss: false,
      deptId: null,
      lossData: [
        {
          totalLossVal: null,
          date: null,
          assetResultList: [
            {
              assetName: null,
              category: null,
              nowQuantity: null,
              lossQuantity: null,
              lossVal: null
            }
          ]
        }
      ],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        orderNumber: [
          { required: true, message: "单据编号不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "任务名称不能为空", trigger: "blur" }
        ],
        inventoryDepartment: [
          { required: true, message: "盘点部门不能为空", trigger: "blur" }
        ],
        inventoryBy: [
          { required: true, message: "盘点人不能为空", trigger: "blur" }
        ],
        inventoryDate: [
          { required: true, message: "盘点日期不能为空", trigger: "blur" }
        ],
        inventoryLocation: [
          { required: true, message: "盘点位置不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDeptTree()
  },
  methods: {
    getCode(number) {
      return selectQrCode(number, Math.random())
    },
    onOpenDetail(number) {
      this.$router.push({
        path: `/inventory/detail?orderNumber=${number}`
      })
    },
    onOpenExportDetail() {
      const queryParams = this.queryParams
      this.exportParams = {
        inventoryDepartment: queryParams.inventoryDepartment,
        inventoryDate: queryParams.inventoryDate,
        inventoryLocation: queryParams.inventoryLocation,
        recordStatus: 1,
      }
      this.openExport = true
    },
    submitExport() {
      this.download('inventory/detail/export/detail', {
        ...this.exportParams
      }, `资产盘点报表_${new Date().getTime()}.xlsx`)
      this.openExport = false
    },
    onOpenLoss() {
      this.openLoss = true
    },
    onQueryLoss() {
      if (this.deptId === null) {
        this.$modal.msgWarning("部门不能为空");
        return
      }
      getDepAssetLossTb(this.deptId).then(res => {
        this.lossData = res.data
        console.log('资产报表', this.lossData)
      })
    },
    onLossExport() {
      if (this.deptId === null) {
        this.$modal.msgWarning("部门不能为空");
        return
      }
      const deptId = this.deptId
      this.download('inventory/inventory/exportDepAssetLossTb/' + deptId, {
      }, `资产报表_${new Date().getTime()}.xlsx`)
      this.openExport = false
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    onSelectUser(info) {
      this.openUserSearch = false
      this.form.inventoryBy = info.userName
    },
    tenantIdnormalizer(node) {
      return {
        id: node.id,
        label: node.label,
        children: node.children
      }
    },
    /** 查询资产盘点记录列表 */
    getList() {
      this.loading = true;
      this.getTreeSelect()
      listDept().then((response) => {
        this.arr = response.data
      });
      listInventory(this.queryParams).then(response => {
        this.inventoryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getTreeSelect() {
      treeSelect().then(res => {
        this.locationOption = res.data
      })
    },
    //获取公司名
    companyName(val){
      let num = parseInt(val)
      let arr2 = this.arr.filter(item => item.deptId===num);
      return arr2[0].deptName
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderNumber: null,
        name: null,
        inventoryDepartment: null,
        inventoryBy: null,
        inventoryDate: null,
        inventoryLocation: null,
        inventoryStatus: null,
        inventoryResult: null,
        recordStatus: null,
        remark: null,
        createdTime: null,
        updatedTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      let count = 0;
      if (selection.length) {
        selection.forEach(item => {
          if (item.inventoryStatus > 1) {
            this.$refs.elTable.toggleRowSelection(item, false)
            count++;
          }
        });
      }
      if (count > 0) {
        this.$modal.msgWarning("盘点已进行");
      }
      this.ids = selection.filter(item => item.inventoryStatus > 1).map(item => item.id)
      this.single = (selection.length - count) !==1
      this.multiple = !(selection.length - count)
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加资产盘点记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getInventory(id).then(response => {
        this.form = response.data;
        this.form.inventoryLocation = response.data.inventoryLocation.split(",").map(Number)
        this.open = true;
        this.title = "修改资产盘点记录";
      });
    },
    /** 提交按钮 */
    submitForm(recordStatus) {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.recordStatus = recordStatus
          this.form.inventoryLocation = String(this.form.inventoryLocation)
          if (this.form.id != null) {
            updateInventory(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInventory(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除资产盘点记录编号为"' + ids + '"的数据项？').then(function() {
        return delInventory(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('inventory/inventory/export', {
        ...this.queryParams
      }, `inventory_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style lang="less" scoped>
/deep/ .vue-treeselect {
  display: inline-block;
}
.queryForm {
  /deep/ .vue-treeselect {
    width: 205px;
    height: 32px;
  }
}
.clickNumber{
  color: #409EFF;

  &:hover{
    cursor: pointer;
    text-decoration: underline;
  }
}
</style>
