<template>
  <div class="app-container row-container">
    <div class="head-container">
      <div v-if="crud.props.searchToggle" class="head-search">
        <el-input v-model="query.billNo" clearable size="small" placeholder="输入盘点单号搜索" prefix-icon="el-icon-search" style="width: 225px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <el-select v-model="query.warehouseId" clearable size="small" placeholder="所属仓库" class="filter-item" style="width: 120px" @change="crud.toQuery">
          <i slot="prefix" class="iconfont icon-zhuangtai" />
          <el-option
            v-for="(item,index) in warehouseOptions"
            :key="index"
            :label="item.warehouseName"
            :value="item.id"
          />
        </el-select>
        <el-select v-model="query.status" clearable size="small" placeholder="盘点状态" class="filter-item" style="width: 120px" @change="crud.toQuery">
          <i slot="prefix" class="iconfont icon-zhuangtai" />
          <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-button class="filter-item filter-search" size="mini" type="success" icon="el-icon-search" @click="crud.toQuery">搜索</el-button>
        <el-button class="filter-item  filter-refresh" size="mini" type="warning" icon="el-icon-refresh-left" @click="resetQuery()">重置</el-button>
      </div>
      <crudOperation :permission="permission">
        <template v-slot:middle>
          <!-- <el-button :loading="addLoading" size="mini" @click="addStockTakeBill">
            <i class="iconfont icon-xinzeng" />
            新增
          </el-button> -->
          <!-- <el-button slot="reference" size="mini" :loading="crud.delAllLoading" :disabled="crud.selections.length === 0" @click="toDelete(crud.selections)">
            <i class="iconfont icon-shanchu" />
            删除
          </el-button> -->
          <!-- <el-button size="mini" :disabled="crud.selections.length === 0">
            <i class="iconfont icon-jiesuan" />
            结算
          </el-button> -->
          <!-- <el-button :loading="crud.downloadLoading" size="mini" :disabled="crud.selections.length === 0" @click="doExport(crud.selections)">
            <i class="iconfont icon-daochu" />
            导出
          </el-button> -->
        </template>
        <!-- <template v-slot:right>
          <el-button :loading="clearCacheLoading" size="mini" style="background-color: #ed4a41; border-color: #ed4a41; color: #fff;" @click="clearCacheDatas">
            <i class="iconfont icon-shanchu" />
            清空缓存
          </el-button>
        </template> -->
      </crudOperation>
    </div>
    <div class="container-wrap">
      <span class="right-top-line" />
      <span class="left-bottom-line" />
      <el-table
        ref="table"
        v-loading="crud.loading"
        class="archives-table"
        highlight-current-row
        stripe
        style="width: 100%;"
        height="calc(100vh - 330px)"
        :data="crud.data"
        @selection-change="crud.selectionChangeHandler"
        @row-click="clickRowHandler"
        @row-dblclick="handleRowDblClick"
      >
        <el-table-column type="selection" align="center" width="55" />
        <el-table-column prop="billNo" label="任务编号" min-width="180px" :show-overflow-tooltip="true" />
        <!-- <el-table-column prop="stockName" label="任务名称" min-width="150px" />
        <el-table-column prop="stockManager" label="负责人" min-width="100px" /> -->
        <el-table-column prop="warehouseName" label="所属仓库" min-width="160px" :show-overflow-tooltip="true" />
        <!-- <el-table-column prop="stockExecutor" label="盘点执行人" min-width="120px" /> -->

        <el-table-column prop="stockNum" label="总数" min-width="80px" align="right" />
        <el-table-column prop="correctQty" label="账实相符数" min-width="120px" align="right" />
        <el-table-column prop="excessQty" label="盘盈数" min-width="80px" align="right" />
        <el-table-column prop="missingQty" label="盘亏数" min-width="80px" align="right" />
        <el-table-column prop="status" label="盘点状态" align="center" min-width="100px">
          <template slot-scope="scope">
            <span v-if="(scope.row.status || '').toString().trim() === '0'" class="row-state row-lending ">未盘点</span>
            <span v-if="(scope.row.status || '').toString().trim() === '-1'" class="row-state row-lending state-active">已终止</span>
            <span v-if="(scope.row.status || '').toString().trim() === '1'" class="row-state row-warehousing  state-active">盘点中</span>
            <span v-if="(scope.row.status || '').toString().trim() === '2'" class="row-state row-binding  state-active">已完成</span>
          </template>
        </el-table-column>
        <el-table-column prop="takeDate" label="发起时间" width="150px">
          <template slot-scope="scope">
            <div>{{ scope.row.takeDate | parseTime }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="takeStart" label="盘点开始时间" width="150px">
          <template slot-scope="scope">
            <div>{{ scope.row.takeStart | parseTime }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="takeEnd" label="盘点结束时间" width="150px">
          <template slot-scope="scope">
            <div>{{ scope.row.takeEnd | parseTime }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="210px">
          <template slot-scope="scope">
            <el-button :loading="scope.row.deleteLoading" style="background-color: #F65163; border-color:#F65163; color: #fff;" @click="toDelete(scope.row)">
              删除
            </el-button>
            <el-button :loading="scope.row.settleLoading" style="background-color: #1AAE93; border-color:#1AAE93; color: #fff;" @click="handleSettle(scope.row)">
              结算
            </el-button>
            <el-button :loading="scope.row.exportLoading" @click="handleExport(scope.row)">
              导出
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination v-if="crud.data.length!==0" />
    </div>

    <el-dialog width="1000px" :close-on-click-modal="false" :modal-append-to-body="false" append-to-body :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" class="group-form">
      <span class="dialog-right-top" />
      <span class="dialog-left-bottom" />
      <div class="setting-dialog">
        <el-form ref="form" :inline="true" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="所属部门" prop="departmentname">
            <el-select v-model="form.departmentname" placeholder="请选择" style="width: 300px;" @change="handleDepartmentChange">
              <el-option
                v-for="(item,index) in departmentOptions"
                :key="index"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="使用者" prop="user">
            <el-select v-model="form.user" placeholder="请选择" style="min-width: 200px;">
              <el-option
                v-for="(item,index) in userOptions"
                :key="index"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item> -->
          <el-button type="primary" size="small" :loading="fetchLoading" @click="fetchAssetsData(true)">查询</el-button>
        </el-form>
        <div v-if="showFilterList" class="filter-list">
          <!-- <div v-if="fetchLoading">
            <el-icon class="is-loading"><i class="el-icon-loading" /></el-icon> 加载中...
          </div>
          <div v-else> -->
          <div>约<span>{{ totalAssets }}</span>项资产</div>
          <el-table v-loading="fetchLoading" stripe style="width: 100%; margin-top: 20px;" height="calc(100vh - 460px)" :data="listTable">
            <!-- <el-table-column type="index" label="序号" align="center" width="55" /> -->
            <el-table-column label="序号" align="center" width="55">
              <template slot-scope="scope">
                {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
              </template>
            </el-table-column>
            <!-- <el-table-column prop="result" label="结果">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.result === 1" type="success">正常</el-tag>
                <el-tag v-if="scope.row.result === 2" type="error">盘亏</el-tag>
                <el-tag v-if="scope.row.result === 3">盘盈</el-tag>
              </template>
            </el-table-column> -->
            <el-table-column prop="mark" label="资产编码" min-width="220px" :show-overflow-tooltip="true" />
            <el-table-column prop="name" label="资产名称" min-width="220px" :show-overflow-tooltip="true" />
            <!-- <el-table-column prop="remark" label="盘点备注" min-width="100px" />
            <el-table-column prop="status" label="资产状态" min-width="100px" /> -->
            <el-table-column prop="capitaltyepname" label="资产类型" min-width="100px" />
            <el-table-column prop="departmentname" label="使用部门" min-width="260px" :show-overflow-tooltip="true" />
            <el-table-column prop="resourcename" label="使用人" min-width="120px" />
            <!-- <el-table-column prop="blongsubcompanyname" label="所属单位" min-width="180px" :show-overflow-tooltip="true" /> -->
            <el-table-column prop="blongdepartmentname" label="所属部门" min-width="180px" :show-overflow-tooltip="true" />
            <el-table-column prop="glrname" label="管理人" min-width="120px" />
            <el-table-column prop="cfd" label="存放地" min-width="260px" :show-overflow-tooltip="true" />
          </el-table>
          <div v-if="listTable.length !== 0" style="margin-top: 10px; display: flex; justify-content: flex-end;">
            <el-pagination
              style="margin: 10px 0 !important;"
              :current-page="currentPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next"
              :total="totalAssets"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
          <!-- </div> -->
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button style="width: 84px !important;" :loading="crud.status.cu === 2" type="primary" :disabled="!hasAssets" @click="crud.submitCU">生成盘点单</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 资产详情对话框 -->
    <el-dialog
      class="inventory-detail-dialog"
      :visible.sync="detailDialogVisible"
      title="盘点任务详情"
      width="1000px"
      append-to-body
      :close-on-click-modal="false"
      :modal-append-to-body="false"
    >
      <div v-if="selectedTask" class="task-detail">
        <!-- 任务基本信息 -->
        <el-table class="archives-table" stripe style="width: 100%;" :data="selectedTask">
          <el-table-column prop="billNo" label="任务编号" min-width="180px" :show-overflow-tooltip="true" />
          <!-- <el-table-column prop="stockName" label="任务名称" min-width="150px" />
          <el-table-column prop="stockManager" label="负责人" min-width="100px" /> -->
          <el-table-column prop="warehouseName" label="所属仓库" min-width="300px" :show-overflow-tooltip="true" />
          <!-- <el-table-column prop="stockExecutor" label="盘点执行人" min-width="120px" /> -->
          <el-table-column prop="takeDate" label="发起时间" width="180px">
            <template slot-scope="scope">
              <div>{{ scope.row.takeDate | parseTime }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="takeStart" label="盘点开始时间" width="180px">
            <template slot-scope="scope">
              <div>{{ scope.row.takeStart | parseTime }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="takeEnd" label="盘点结束时间" width="180px">
            <template slot-scope="scope">
              <div>{{ scope.row.takeEnd | parseTime }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="stockNum" label="总数" min-width="80px" />
          <el-table-column prop="correctQty" label="账实相符数" min-width="120px" />
          <el-table-column prop="excessQty" label="盘盈数" min-width="80px" />
          <el-table-column prop="missingQty" label="盘亏数" min-width="80px" />
          <el-table-column prop="status" label="盘点状态" align="center" min-width="100px">
            <template slot-scope="scope">
              <span v-if="(scope.row.status || '').toString().trim() === '0'" class="row-state row-lending">未盘点</span>
              <span v-if="(scope.row.status || '').toString().trim() === '-1'" class="row-state row-lending state-active">已终止</span>
              <span v-if="(scope.row.status || '').toString().trim() === '1'" class="row-state row-warehousing  state-active">盘点中</span>
              <span v-if="(scope.row.status || '').toString().trim() === '2'" class="row-state row-binding  state-active">已完成</span>
            </template>
          </el-table-column>
        </el-table>
        <!-- 盘点清单 -->
        <div class="inventory-list">
          <div style="display: flex; justify-content: space-between; align-items: center;">
            <ul class="tab-nav">
              <li :class="{'active-tab-nav': tabIndex == 0}" @click="changeActiveTab(0)">盘点清单</li>
              <li :class="{'active-tab-nav': tabIndex == 1}" @click="changeActiveTab(1)">盘盈列表</li>
            </ul>
            <div>
              <el-select v-if="tabIndex===0" v-model="taskResult" clearable size="small" placeholder="状态" class="filter-item" style="width: 80px" @change="doSearch">
                <el-option v-for="item in taskResultOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
              <el-input
                v-model="keyWord"
                size="small"
                clearable
                placeholder="请输入关键字搜索"
                style="width: 300px;"
                class="input-prepend filter-item"
                @keyup.enter.native="doSearch"
                @clear="doSearch"
              >
                <el-select slot="prepend" v-model="optionVal" style="width: 92px">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-input>
              <el-button class="filter-item filter-search" size="mini" type="success" icon="el-icon-search" @click="doSearch">搜索</el-button>
            </div>
          </div>
          <el-table v-loading="inventoryLoading" stripe style="width: 100%;" height="calc(100vh - 460px)" :data="inventoryList">
            <el-table-column label="序号" align="center" width="55">
              <template slot-scope="scope">
                {{ (inventoryPage - 1) * inventoryPageSize + scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column v-if="tabIndex === 0" prop="taskResult" label="结果">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.taskResult === 0">未盘</el-tag>
                <el-tag v-if="scope.row.taskResult === 1" type="success">正常</el-tag>
                <el-tag v-if="scope.row.taskResult === 2" type="error">盘亏</el-tag>
              </template>
            </el-table-column>
            <el-table-column v-else prop="taskResult" label="结果">
              <template>
                <el-tag class="other-tag">盘盈</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="assetMark" label="资产编码" min-width="220px" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span v-if="tabIndex === 0">{{ scope.row.assetMark }}</span>
                <span v-else>
                  {{
                    (scope.row.assetInfo && scope.row.assetInfo.mark)
                      ? scope.row.assetInfo.mark
                      : (scope.row.superfluous && scope.row.superfluous.mark) || '-'
                  }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="assetName" label="资产名称" min-width="180px" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span v-if="tabIndex === 0">{{ scope.row.assetName }}</span>
                <span v-else>
                  {{ scope.row.assetInfo ? scope.row.assetInfo.name : '' }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="taskRemark" label="盘点备注" min-width="100px">
              <template slot-scope="scope">
                <span v-if="tabIndex === 0">{{ scope.row.taskRemark }}</span>
                <span v-else>
                  {{ scope.row.assetInfo ? scope.row.assetInfo.remark : '' }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="capitalStatus" label="资产状态" min-width="100px">
              <template slot-scope="scope">
                <span v-if="tabIndex === 0">{{ scope.row.capitalStatus }}</span>
                <span v-else>
                  {{ scope.row.assetInfo ? scope.row.assetInfo.capitalStatus : '' }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="capitaltypename" label="资产类型" min-width="100px">
              <template slot-scope="scope">
                <span v-if="tabIndex === 0">{{ scope.row.capitaltypename }}</span>
                <span v-else>
                  {{ scope.row.assetInfo ? scope.row.assetInfo.capitaltypename : '' }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="blongdepartmentname" label="所属部门" min-width="160px" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span v-if="tabIndex === 0">{{ scope.row.blongdepartmentname }}</span>
                <span v-else>
                  {{ scope.row.assetInfo ? scope.row.assetInfo.blongdepartmentname : '' }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="departmentname" label="使用部门" min-width="160px" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span v-if="tabIndex === 0">{{ scope.row.departmentname }}</span>
                <span v-else>
                  {{ scope.row.assetInfo ? scope.row.assetInfo.departmentname : '' }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="resourcename" label="使用人" min-width="100px" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span v-if="tabIndex === 0">{{ scope.row.resourcename }}</span>
                <span v-else>
                  {{ scope.row.assetInfo ? scope.row.assetInfo.resourcename : '' }}
                </span>
              </template>
            </el-table-column>
            <!-- <el-table-column prop="blongsubcompanyname" label="所属单位" min-width="180px" :show-overflow-tooltip="true" />
            <el-table-column prop="blongdepartmentname" label="所属部门" min-width="180px" :show-overflow-tooltip="true" /> -->
            <el-table-column prop="glrname" label="管理人" min-width="100px" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span v-if="tabIndex === 0">{{ scope.row.glrname }}</span>
                <span v-else>
                  {{ scope.row.assetInfo ? scope.row.assetInfo.glrname : '' }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="cfd" label="存放地" min-width="260px" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span v-if="tabIndex === 0">{{ scope.row.cfd }}</span>
                <span v-else>
                  {{ scope.row.assetInfo ? scope.row.assetInfo.cfd : '' }}
                </span>
              </template>
            </el-table-column>
            <el-table-column v-if="tabIndex === 1" prop="taskTime" label="盘点时间" width="160px">
              <template slot-scope="scope">
                <!-- 有资产信息 → 显示 - -->
                <span v-if="scope.row.assetInfo"> - </span>

                <!-- 没有资产信息 → 安全显示时间，没有时间也显示 - -->
                <span v-else-if="scope.row.superfluous && scope.row.superfluous.taskTime">
                  {{ scope.row.superfluous.taskTime | parseTime }}
                </span>

                <!-- 都没有 → 显示 - -->
                <span v-else> - </span>
              </template>
            </el-table-column>
          </el-table>
          <div style="margin-top: 10px; display: flex; justify-content: flex-end;">
            <el-pagination
              :key="`tab-${tabIndex}-${inventoryTotal}`"
              :current-page="inventoryPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="inventoryPageSize"
              layout="total, sizes, prev, pager, next"
              :total="inventoryTotal"
              style="margin: 20px 0 !important;"
              @size-change="handleInventorySizeChange"
              @current-change="handleInventoryCurrentChange"
            />
          </div>
        </div>
      </div>
      <div v-else>
        暂无数据
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import { getAssetDeptTree } from '@/api/system/dept'
import crudAsset, { FetchInitAssetInfo, FetchStockTakeDetailsByTaskId, FetchStockTakeSuperfluousByTaskId, FetchStockSettle, FetchDeleteStockTake, add } from '@/api/asset/index'
import { FetchWarehouseTree } from '@/api/assetDevice/index'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import crudOperation from '@crud/CRUD.operation'
import pagination from '@crud/Pagination'
// import { exportFile } from '@/utils/index'
import qs from 'qs'
import { mapGetters } from 'vuex'

// user: null, id: null, departmentname: null
const defaultForm = { }
export default {
  name: 'Stocktaking',
  components: { pagination, crudOperation },
  cruds() {
    return CRUD({ title: '资产盘点', url: 'api/stocktake/initStockTakeBill', crudMethod: { ...crudAsset }, optShow: {
      add: false,
      edit: false,
      del: false,
      reset: true,
      download: false,
      group: false
    }})
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  data() {
    return {
      clearCacheLoading: false,
      addLoading: false,
      settleLoading: false,
      permission: {
        add: [],
        edit: [],
        del: []
      },
      departmentOptions: [],
      userOptions: [
        { id: 1, name: '张三' },
        { id: 2, name: '李四' },
        { id: 3, name: '王五' }
      ],
      rules: {
        departmentname: [
          { required: true, message: '请选择所属部门', trigger: 'change' }
        ]
        // user: [
        //   { required: true, message: '请选择使用者', trigger: 'change' }
        // ]
      },
      keyWord: '',
      optionVal: 'assetMark',
      options: [
        { value: 'assetMark', label: '资产编号' },
        { value: 'assetName', label: '资产名称' }
      ],
      fetchLoading: false,
      showFilterList: false,
      listTable: [],
      totalAssets: 0,
      currentPage: 1,
      pageSize: 10,
      detailDialogVisible: false,
      selectedTask: [],
      inventoryList: [],
      inventoryLoading: false,
      inventoryPage: 1,
      inventoryPageSize: 10,
      inventoryTotal: 0,
      statusOptions: [
        { value: 0, label: '未盘点' },
        { value: 1, label: '盘点中' },
        // { value: -1, label: '已终止' },
        { value: 2, label: '已完成' }
      ],
      warehouseOptions: [],
      query: {
        billNo: '',
        warehouseId: '',
        status: ''
      },
      tabIndex: 0,
      taskResult: '',
      taskResultOptions: [
        { value: 0, label: '未盘' },
        { value: 1, label: '正常' },
        { value: 2, label: '盘亏' }
      ],
      assetMark: '',
      assetName: ''
    }
  },
  computed: {
    ...mapGetters([
      'baseApi',
      'user'
    ]),
    hasAssets() {
      return this.totalAssets > 0
    }
  },
  created() {
    // this.getAssetDeptTree()
    FetchWarehouseTree().then(res => {
      this.warehouseOptions = res
    }).catch(() => {
    })
  },
  mounted() {
  },
  methods: {
    [CRUD.HOOK.beforeRefresh]() {
      // 传递搜索参数
      console.log('this.user', this.user)
      this.crud.params.billNo = this.query.billNo
      this.crud.params.warehouseId = this.query.warehouseId
      this.crud.params.status = this.query.status
      this.crud.query.userId = this.user.id

      // 保存原始参数
      this.originalPage = this.crud.page.page
      this.originalSize = this.crud.page.size
      // 添加pageNo和pageSize参数
      this.crud.params.pageNo = this.crud.page.page
      this.crud.params.pageSize = this.crud.page.size
      // 清空page和size参数
      this.crud.params.page = undefined
      this.crud.params.size = undefined
    },
    [CRUD.HOOK.afterRefresh]() {
      // 恢复原始参数
      if (this.originalPage !== undefined) {
        this.crud.page.page = this.originalPage
        this.crud.page.size = this.originalSize
        // 移除pageNo和pageSize参数
        delete this.crud.params.pageNo
        delete this.crud.params.pageSize
        delete this.crud.params.page
        delete this.crud.params.size
      }

      // 为每一行数据添加loading状态
      this.crud.data.forEach(item => {
        if (!item.deleteLoading) {
          this.$set(item, 'deleteLoading', false)
        }
        if (!item.settleLoading) {
          this.$set(item, 'settleLoading', false)
        }
        if (!item.exportLoading) {
          this.$set(item, 'exportLoading', false)
        }
      })
    },
    // 新增前
    [CRUD.HOOK.beforeToAdd](crud, form) {
      // 重置表单数据
      crud.form.departmentname = null
      // crud.form.user = null
      // 重置相关状态
      this.showFilterList = false
      this.listTable = []
      this.totalAssets = 0
      this.currentPage = 1
      this.pageSize = 10
      // 重置表单验证状态
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
    },
    // 编辑前
    [CRUD.HOOK.beforeToEdit](crud, form) {
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      console.log(crud.form)
      return true
    },
    // 关闭弹框前的操作
    [CRUD.HOOK.beforeAddCancel](crud) {
      // 重置表单数据
      crud.form.departmentname = null
      // crud.form.user = null
      // 重置相关状态
      this.showFilterList = false
      this.listTable = []
      this.totalAssets = 0
      this.currentPage = 1
      this.pageSize = 10
      // 重置表单验证状态
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
    },
    // getAssetDeptTree() {
    //   getAssetDeptTree().then(res => {
    //     this.departmentOptions = res
    //   })
    // },
    searchChange(val) {
      if (val) {
        this.keyWord = ''
      }
    },
    resetQuery() {
      // 重置查询参数
      this.query.billNo = ''
      this.query.warehouseId = ''
      this.query.status = ''
      this.crud.toQuery()
    },
    // 触发单选
    clickRowHandler(row) {
      this.$refs.table.clearSelection()
      this.$refs.table.toggleRowSelection(row)
    },
    handleSettle(row) {
      // if ((row.status || '').toString().trim() !== '1') {
      //   this.$message({ message: '当前任务不在盘点中，不可结算', type: 'error', offset: 8 })
      //   return
      // }
      row.settleLoading = true
      FetchStockSettle(row.id).then(res => {
        row.settleLoading = false
        if (res.data === null) {
          this.$message({ message: res.message, type: 'error', offset: 8 })
        } else {
          this.$message({ message: '结算操作成功', type: 'success', offset: 8 })
          this.crud.refresh()
        }
      }).catch(err => {
        row.settleLoading = false
        console.log(err)
        this.$message({ message: '结算操作失败', type: 'error', offset: 8 })
      })
    },
    handleExport(row) {
      row.exportLoading = true
      let loadingClosed = false

      const params = { id: row.id }
      const exportUrl = this.baseApi + '/api/stocktake/exportStockTakeData?' + qs.stringify(params, { indices: false })

      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = exportUrl

      document.body.appendChild(link)
      link.click()

      // 正常关闭
      const timer = setTimeout(() => {
        if (!loadingClosed) {
          loadingClosed = true
          row.exportLoading = false
          document.body.removeChild(link)
        }
      }, 1500)

      // 兜底最长等待3秒
      setTimeout(() => {
        if (!loadingClosed) {
          clearTimeout(timer)
          row.exportLoading = false
        }
      }, 3000)
    },
    doSearch() {
      if (this.optionVal === 'assetMark') {
        this.assetMark = this.keyWord
        this.assetName = ''
      } else {
        this.assetName = this.keyWord
        this.assetMark = ''
      }
      this.inventoryPage = 1
      this.tabIndex === 1 ? this.getStockTakeSuperfluousByTaskId() : this.fetchInventoryList()
    },
    toDelete(datas) {
      this.$confirm('此操作将删除当前所选盘点任务' + '<span>你是否还要继续？</span>', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        datas.deleteLoading = true
        FetchDeleteStockTake(datas.id).then((res) => {
          datas.deleteLoading = false
          if (res.data === null) {
            this.$message({ message: res.message, type: 'error', offset: 8 })
          } else {
            this.$message({ message: '删除成功', type: 'success', offset: 8 })
          }
          this.crud.refresh()
        }).catch(err => {
          datas.deleteLoading = false
          console.log(err)
        })
      }).catch(() => {
      })
    },
    // 清空缓存
    // clearCacheDatas(datas) {
    //   this.$confirm('此操作将清空盘点缓存数据' + '<span>你是否还要继续？</span>', '提示', {
    //     confirmButtonText: '继续',
    //     cancelButtonText: '取消',
    //     type: 'warning',
    //     dangerouslyUseHTMLString: true
    //   }).then(() => {
    //     this.clearCacheLoading = true
    //   }).catch(() => {
    //     this.clearCacheLoading = false
    //   })
    // },
    // 获取资产数据
    fetchAssetsData(isBtn) {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (isBtn) {
            this.fetchLoading = true
          }
          this.showFilterList = true
          const params = {
            'departmentname': this.crud.form.departmentname,
            'pageNo': this.currentPage,
            'pageSize': this.pageSize
          }
          FetchInitAssetInfo(params).then(res => {
            console.log('res', res)
            this.listTable = res.records
            this.totalAssets = res.total
            this.fetchLoading = false
          }).catch(err => {
            console.log(err)
            this.$message({ message: '获取数据失败', type: 'error', offset: 8 })
            this.fetchLoading = false
          })
        }
      })
    },
    // 处理分页大小变化
    handleSizeChange(size) {
      this.pageSize = size
      this.fetchAssetsData()
    },
    // 处理当前页码变化
    handleCurrentChange(current) {
      this.currentPage = current
      this.fetchAssetsData()
    },
    // 处理部门选择变化
    handleDepartmentChange() {
      this.currentPage = 1
      this.fetchAssetsData()
    },
    // 处理双击行事件
    handleRowDblClick(row) {
      this.tabIndex = 0
      this.selectedTask = [row]
      this.detailDialogVisible = true

      this.taskResult = ''
      this.assetMark = ''
      this.assetName = ''
      this.keyWord = ''
      this.inventoryPage = 1
      this.fetchInventoryList()
    },
    changeActiveTab(index) {
      this.tabIndex = index
      this.inventoryPage = 1
      this.taskResult = ''
      this.assetMark = ''
      this.assetName = ''
      this.keyWord = ''
      this.tabIndex === 1 ? this.getStockTakeSuperfluousByTaskId() : this.fetchInventoryList()
    },
    // 获取盘点清单数据
    fetchInventoryList() {
      if (!this.selectedTask) return
      this.inventoryLoading = true
      const params = {
        taskId: this.selectedTask[0].id,
        pageNo: this.inventoryPage,
        pageSize: this.inventoryPageSize,
        taskResult: this.taskResult,
        assetMark: this.assetMark,
        assetName: this.assetName
      }
      FetchStockTakeDetailsByTaskId(params).then(res => {
        this.inventoryList = res.records
        this.inventoryTotal = res.total
        this.inventoryLoading = false
      }).catch(err => {
        console.log(err)
        this.$message({ message: '获取数据失败', type: 'error', offset: 8 })
        this.inventoryLoading = false
      })
    },
    // 获取盘盈列表数据
    getStockTakeSuperfluousByTaskId() {
      if (!this.selectedTask) return
      this.inventoryLoading = true
      const params = {
        taskId: this.selectedTask[0].id,
        pageNo: this.inventoryPage,
        pageSize: this.inventoryPageSize,
        assetMark: this.assetMark,
        assetName: this.assetName
      }
      FetchStockTakeSuperfluousByTaskId(params).then(res => {
        this.inventoryList = res.data.records
        this.inventoryTotal = res.data.total
        this.inventoryLoading = false
      }).catch(err => {
        console.log(err)
        this.$message({ message: '获取数据失败', type: 'error', offset: 8 })
        this.inventoryLoading = false
      })
    },
    // 处理盘点清单分页大小变化
    handleInventorySizeChange(size) {
      this.inventoryPage = 1
      this.inventoryPageSize = size
      this.tabIndex === 1 ? this.getStockTakeSuperfluousByTaskId() : this.fetchInventoryList()
    },
    // 处理盘点清单当前页码变化
    handleInventoryCurrentChange(current) {
      this.inventoryPage = current
      this.tabIndex === 1 ? this.getStockTakeSuperfluousByTaskId() : this.fetchInventoryList()
    },
    // 直接触发新增接口
    addStockTakeBill() {
      this.addLoading = true
      add({}).then(res => {
        if (res.data === null) {
          this.$message({ message: res.message, type: 'error', offset: 8 })
        } else {
          this.$message({ message: '新增成功', type: 'success', offset: 8 })
          this.crud.refresh()
        }
        this.addLoading = false
      }).catch(err => {
        console.log(err)
        this.$message({ message: '新增失败', type: 'error', offset: 8 })
        this.addLoading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.group-form{
  .el-form-item{
    &:nth-child(odd){
      margin-right: 0;
    }
    &.form-item-style{
      margin-right: 40px;
    }
    ::v-deep .el-form-item__content{
       width: 300px !important;
    }
  }
}

::v-deep .input-prepend .el-input__inner{
  padding-left: 100px;
}

::v-deep .el-tag{
  &.el-tag--small{
    color: #0348f3 !important;
    background-color: #eef5fe !important;
    border-color:  #c1dbfc !important;
  }
  &.el-tag--success {
    background-color: #e7faf0 !important;
    border-color: #d0f5e0!important;
    color: #13ce66!important;
  }
  &.el-tag--info {
    background-color: #f4f4f5 !important;
    border-color: #f4f4f5!important;
    color: #909399!important;
  }
  &.el-tag--error {
    background-color: #fbc0b5  !important;
    border-color: #fcab9d  !important;
    color: #ed4a41!important;
  }
  &.other-tag{
    color: #FF8329 !important;
    background-color: #FFF3E5 !important;
    border-color:  #FEBD98 !important;
  }
}

.task-detail {
  padding: 10px 0;
}

.task-info {
  margin-bottom: 20px;
}

.task-info h3,
.inventory-list h3 {
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.inventory-list {
  margin-top: 30px;
}

.inventory-list .el-table {
  margin-top: 10px;
}

.inventory-detail-dialog{
  ::v-deep .el-dialog__body{
    padding: 0 !important;
  }
}
.el-table .el-button{
  padding: 7px 10px !important;
}

.tab-nav{
  display: flex;
  justify-content: flex-start;
  margin: 25px 0 18px 0;
  font-size: 16px;
  font-weight: bold;
  color: #333;
  // padding: 0 0 0 20px;
  border-bottom: 1px solid #EDEFF3;
  li{
    margin-right: 30px;
    cursor: default;
    &.active-tab-nav{
      padding-bottom: 10px;
      color: #0348F3;
      border-bottom: 3px solid #0348F3;
    }
  }
}
</style>
