<template>
  <div class="page-home">
    <div class="search-wrap" v-if="IsPermission(route, 'QUERY_BASE')">
      <el-select clearable v-model="searchForm.inventoryType" style="width: 200px" placeholder="请选择设备类型">
        <el-option v-for="item in inventoryTypeList" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-select clearable v-model="searchForm.brand" style="width: 260px" placeholder="请选择设备厂商（先选设备类型）">
        <template v-slot="scope">
          <span v-if="searchForm.inventoryType == 'CARD'">
            <el-option v-for="item in cardManufacturerList" :key="item.value" :label="item.label" :value="item.value" />
          </span>
          <span v-if="searchForm.inventoryType == 'OBU'">
            <el-option v-for="item in manufacturerList" :key="item.value" :label="item.label" :value="item.value" />
          </span>
        </template>
      </el-select>
      <el-select clearable v-model="searchForm.version" style="width: 200px" placeholder="请选择设备型号">
        <el-option v-for="item in modelList" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-select clearable v-model="searchForm.applyStatus" style="width: 200px" placeholder="请选择申请状态">
        <el-option v-for="item in resultList" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-date-picker unlink-panels v-model="value1" type="daterange" range-separator="到" start-placeholder="开始日期"
        end-placeholder="结束日期" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
        @change="dateChangeHandle" />
      <el-button type="success" icon="search" @click="btnSearch">
        搜索
      </el-button>
      <el-button type="warning" icon="refreshLeft" @click="refreshLeft">
        重置
      </el-button>
    </div>
    <div class="table-btn">
      <el-button v-if="IsPermission(route, 'STORAGE_EQUIPMENT')" type="primary" @click="addHandle" icon="Plus">
        设备入库-备货
      </el-button>
      <el-button v-if="IsPermission(route, 'BATCH_CONFIRM_WAREHOUSEING')" type="success" @click="sureMoreHandle"
        v-loading="btnLoading">
        批量确认入库
      </el-button>
    </div>
    <div class="table-list">
      <!--  table-layout="auto" -->
      <el-table :data="tableData" @selection-change="selectionChangeHandle" :border="true" row-key="id"
        v-loading="tableLoding" show-overflow-tooltip>
        <!-- <el-table-column type="expand">
          <template #default="props">
            <div class="table-wrap">
              <el-table :data="props.row.detailList" :border="true">
                <el-table-column label="起始编号" prop="startId" />
                <el-table-column label="结束编号" prop="endId" />
                <el-table-column label="质保期" prop="warranty" />
              </el-table>
            </div>
          </template>
</el-table-column> -->
        <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
        <el-table-column prop="applyNo" label="申请编号" width="100"></el-table-column>
        <el-table-column prop="storeCode" label="仓库编号" width="100"></el-table-column>
        <el-table-column prop="storeCode" label="仓库名称">
          <template v-slot="scope">
            {{ getDictLabel(interfaceLowerListArr, scope.row.storeCode) }}
          </template>
        </el-table-column>
        <!-- deviceFactory -->
        <el-table-column prop="brand" label="厂商" min-width="100">
          <template v-slot="scope">
            <span v-if="scope.row.inventoryType == 'CARD'">
              {{ getDictLabel(cardManufacturerList, scope.row.brand) }}
            </span>
            <span v-if="scope.row.inventoryType == 'OBU'">
              {{ getDictLabel(manufacturerList, scope.row.brand) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="inventoryType" label="采购设备类型" min-width="120">
          <template v-slot="scope">
            <span>{{ getDictLabel(inventoryTypeList, scope.row.inventoryType) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="version" label="设备版本" min-width="100">
          <template v-slot="scope">
            <span>{{ getDictLabel(modelList, scope.row.version) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="applyCount" label="备货数量"></el-table-column>
        <el-table-column prop="applyTime" label="申请时间" width="170">
          <template v-slot="scope">
            <span>{{ scope.row.applyTime.replace('T', ' ') }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="applyStatus" label="状态" width="100">
          <template v-slot="scope">
            <el-tag :type="scope.row.applyStatus === 'CANCEL' ? 'danger' : ''">
              {{ getDictLabel(resultList, scope.row.applyStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="agencyName" label="产权归属"></el-table-column> -->
        <!-- <el-table-column prop="agencyId" label="产权归属"></el-table-column> -->
        <el-table-column label="操作" width="340" fixed="right">
          <template v-slot="scope">
            <el-button type="primary" class="op-btn" @click="editHandle(scope.row)" v-if="
              // (scope.row.applyStatus === 'SUPPLY' ||
              //   scope.row.applyStatus === 'INSTORAGE') &&
              (scope.row.applyStatus === 'NEW') &&
              IsPermission(route, 'EDIT_STOCK_UP')
            ">
              修改备货
            </el-button>
            <el-button type="primary" class="op-btn" @click="deleteHandleShow(scope.row)" v-if="
              (scope.row.applyStatus === 'NEW') &&
              IsPermission(route, 'DEL_STOCK_UP')
            ">
              取消备货
            </el-button>
            <el-button type="primary" class="op-btn" @click="sureHandle(scope.row)" v-if="
              (scope.row.applyStatus === 'NEW') &&
              IsPermission(route, 'CONFIRM_WAREHOUSEING')
            ">
              确认入库
            </el-button>
            <!-- v-if="
              scope.row.applyStatus === 'DONE' &&
              IsPermission(route, 'INFO_LIST')
            " -->
            <el-button type="primary" class="op-btn" @click="viewHandle(scope.row)">
              详情
            </el-button>
            <!-- <el-button type="primary" class="op-btn" @click="restoreHandle(scope.row)" v-if="
              scope.row.applyStatus === 'CANCEL' &&
              IsPermission(route, 'REPLY_STOCK_ORDER')
            ">
              恢复备货单
            </el-button> -->
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-wrap">
      <el-pagination :page-size="paging.pageSize" layout="prev, pager, next" :current-page="paging.currentPage"
        :total="paging.total" @size-change="pagesizeChangeHandle" @current-change="handleCurrentChange" />
    </div>
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="80%" :show-close="false">
      <AddOrUpdate :ref="(el) => (addUpdateRef = el)" @refreshDataList="getList" @closeHandle="handleClose"
        :device-type-list="typeList" :device-model-list="modelList" :manufacturer-list="manufacturerList" />
    </el-dialog>
    <el-dialog v-model="cancelOrderDialog" width="30%" title="取消订单">
      <el-form ref="cancelOrderFormRef" :model="cancelOrderForm" :rules="{
        cancelReason: [
          { required: true, message: '取消原因不能为空', trigger: 'change' },
        ],
      }" label-width="80px">
        <el-form-item label="取消原因" prop="cancelReason">
          <el-input v-trim clearable type="textarea" rows="5" v-model="cancelOrderForm.cancelReason"
            :placeholder="`取消原因`" maxlength="200" show-word-limit></el-input>
        </el-form-item>

      </el-form>
      <template #footer>
        <el-button @click="cancelOrderDialog = false">取 消</el-button>
        <el-button type="primary" @click="deleteHandle()">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<!-- 设备入库管理 -->
<script lang="ts" setup>
import {
  reactive,
  ref,
  toRaw,
  getCurrentInstance,
  onMounted,
  toRefs,
  nextTick,
  computed,
} from 'vue'
import { ElNotification, ElMessage, ElCard, ElMessageBox } from 'element-plus'
import Cookies from 'js-cookie'
import { useDebounce, getDictLabel } from '@/utils/utils'
import BaseService from '@/utils/baseService'
import { IObject } from '@/types/interface'
import AddOrUpdate from './addOrUpdate.vue'
import {
  queryApi,
  statusApi,
  restoreApi,
  cancelApi,
  sureApi,
} from '@/api/inventoryControl/putInstorage'
import {
  manufacturerApi,
  deviceTypeApi,
  deviceModelApi,
} from '@/api/inventoryControl/deviceApply'
import $storeinitData from '@/store/initData' //引入tab vuex
import { useRoute } from 'vue-router'
import { IsPermission } from '@/router/routerUtil'
//或取路由传入过来的对象数据
const route = useRoute()
const tableLoding = ref(false)
const cancelOrderForm = ref({
  cancelReason:''
})
const addUpdateRef = ref()
const state = reactive({
  tableData: [] as IObject[],
  searchForm: {},
  selectList: [] as IObject[],
  paging: {
    pageSize: 10,
    currentPage: 1,
    total: 0,
  },
  btnLoading: false,
})
const dialogVisible = ref(false)
const dialogTitle = ref('')
const value1 = ref()
const typeDialog = ref('')

const inventoryTypeList = computed(() => {
  return $storeinitData.state.dictData['INVENTORY_TYPE'] || []
})
const manufacturerList = computed(() => {
  // return $storeinitData.state.dictData['EQUIPMENT_MANUFACTURER_TYPE'] || []
  return $storeinitData.state.dictData['OBU_BRAND'] || []
})
const cardManufacturerList = computed(() => {
  // return $storeinitData.state.dictData['CARD_EQUIPMENT_MANUFACTURER_TYPE'] || []
  var newVar = $storeinitData.state.dictData['CARD_BRAND'] || [];
  return newVar
})
const typeList = computed(() => {
  // return $storeinitData.state.dictData['DEVICE_TYPE'] || []
  return $storeinitData.state.dictData['OBU_TYPE'] || []
})

const modelList = computed(() => {
  // return $storeinitData.state.dictData['UNIT_TYPE'] || []
  return $storeinitData.state.dictData['DEVICE_VERSION'] || []
})
const resultList = computed(() => {
  return (
    // $storeinitData.state.dictData['INITIAL_EQUIPMENT_PUT_STATUS_TYPE'] || []
    $storeinitData.state.dictData['INV_APPLY_STATUS'] || []
  )
})
const { tableData, searchForm, selectList, paging, btnLoading } = toRefs(state)
function handleCurrentChange(val: number) {
  paging.value.currentPage = val
  getList()
}
// 搜索按钮
function btnSearch() {
  paging.value.currentPage = 1
  getList()
}
const cancelOrderDialog = ref(false)
const rowData = ref()
function deleteHandleShow(row: any) {
  cancelOrderDialog.value = true
  rowData.value = row
}

// 获取仓库状态
function getLowerList() {
  let params = {
    allType: 0
  }
  BaseService.postN('/invw/api/warehouse/getWarehouseIdNames', params).then((res: any) => {
    // console.log(res)
    if (res && res.code === 0) {
      let bizContent = res.data
      let data = bizContent.idNames || [];
      interfaceLowerListArr.value = data
    } else {
      ElMessage.error(res.message)
    }
  })
}
// 搜索重置
function refreshLeft() {
  paging.value.currentPage = 1
  searchForm.value = {}
  value1.value = null
  getList()
}
//pagesize修改
function pagesizeChangeHandle(val: number) {
  paging.value.currentPage = 1
  paging.value.pageSize = val
  getList()
}

function getList() {
  tableLoding.value = true
  let params: any = {
    pageNo: paging.value.currentPage,
    pageSize: paging.value.pageSize,
  }
  let searchFormList = { ...searchForm.value }
  for (let key in searchFormList) {
    if (searchFormList[key]) {
      params[key] = searchFormList[key]
    }
  }
  tableData.value = []
  BaseService.postN('/invw/api/enterApply/page', params).then(
    (res: any) => {
      if (res && res.code === 0) {
        let bizContent = res.data
        let data = bizContent.result || []
        tableData.value = data
        // console.log('bizContent12222', data, tableData.value)
        tableLoding.value = false
        paging.value.total = bizContent.totalCount
      } else {
        tableLoding.value = false
        ElMessage.error(res.message)
      }
    }
  )
}
function dateChangeHandle(val: any) {
  if (val) {
    searchForm.value.applyTimeStart = val[0]
    searchForm.value.applyTimeEnd = val[1]
  } else {
    searchForm.value.applyTimeStart = ''
    searchForm.value.applyTimeEnd = ''
  }
}
// 获取设备厂商
function getManufacturerList() {
  BaseService.postN('/invw/dict/businessmendict').then((res: any) => {
    if (res && res.code === 0) {
      let bizContent = res.data
      let data = bizContent.data || []
      let statusList: any = []
      data.map((item) => {
        statusList.push({
          label: item.item,
          value: item.value,
        })
      })
      // manufacturerList.value = statusList;
    } else {
      ElMessage.error(res.message)
    }
  })
}
//获取设备类型
function getDeviceTypeList() {
  BaseService.postN('/invw/dict/devicetypedict').then((res: any) => {
    if (res && res.code === 0) {
      let bizContent = res.data
      let data = bizContent.data || []
      let statusList: any = []
      data.map((item) => {
        statusList.push({
          label: item.item,
          value: item.value,
        })
      })
      // typeList.value = statusList;
    } else {
      ElMessage.error(res.message)
    }
  })
}
//获取设备型号
function getDeviceModelList() {
  BaseService.postN('/invw/dict/deviceversiontypedict').then((res: any) => {
    if (res && res.code === 0) {
      let bizContent = res.data
      let data = bizContent.data || []
      let statusList: any = []
      data.map((item) => {
        statusList.push({
          label: item.item,
          value: item.value,
        })
      })
      // modelList.value = statusList;
    } else {
      ElMessage.error(res.message)
    }
  })
}
//获取申领状态
function getStatus() {
  BaseService.postN('/invw/dict/inventorystatusdict').then((res: any) => {
    if (res && res.code === 0) {
      let bizContent = res.data
      let data = bizContent.data || []
      let statusList: any = []
      data.map((item) => {
        statusList.push({
          label: item.item,
          value: item.value,
        })
      })
      // resultList.value = statusList;
    } else {
      ElMessage.error(res.message)
    }
  })
}
// 设备入库-备货
function addHandle() {
  dialogVisible.value = true
  dialogTitle.value = '设备入库-备货'
  nextTick(() => {
    addUpdateRef.value.typeOption = 'add'
    addUpdateRef.value.init()
  })
}
// 修改设备入库-备货
function editHandle(row: IObject) {
  dialogVisible.value = true
  dialogTitle.value = '修改设备入库-备货'
  nextTick(() => {
    addUpdateRef.value.typeOption = 'edit'
    addUpdateRef.value.init(row)
  })
}
// 确认入库
function sureHandle(row: IObject) {
  dialogVisible.value = true
  dialogTitle.value = '确认入库'
  nextTick(() => {
    addUpdateRef.value.typeOption = 'sure'
    addUpdateRef.value.init(row)
  })
}
//详情
function viewHandle(row: IObject) {
  dialogVisible.value = true
  dialogTitle.value = '详情'
  nextTick(() => {
    addUpdateRef.value.typeOption = 'view'
    addUpdateRef.value.init(row)
  })
}
// 删除
function deleteHandle(row: IObject) {
  ElMessageBox.confirm('确定要取消备货么？', '', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error',
  })
    .then(() => {
      BaseService.postN('/invw/api/enterApply/cancel', { id: rowData.value.id, reason: cancelOrderForm.value.cancelReason }).then(
        (res: any) => {
          if (res && res.code === 0) {
            getList()
            cancelOrderDialog.value = false
            ElMessage.success('取消备货成功')
          } else {
            ElMessage.error(res.message)
          }
        }
      )
    })
    .catch(() => {
      console.log('取消')
    })
}
// 恢复备货
function restoreHandle(row: IObject) {
  ElMessageBox.confirm('确定要恢复备货么？', '', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error',
  })
    .then(() => {
      BaseService.postN('/invw/inventory/inventoryback', { id: row.id }).then(
        (res: any) => {
          if (res && res.code === 0) {
            getList()
            ElMessage.success('恢复成功')
          } else {
            ElMessage.error(res.message)
          }
        }
      )
    })
    .catch(() => {
      console.log('====取消')
    })
}
//批量确认入库
function sureMoreHandle() {
  btnLoading.value = true
  let list = [...selectList.value]
  if (list.length <= 0) {
    btnLoading.value = false
    ElMessage.warning('请选择需要入库的数据！')
    return
  }
  let ids = list.map((item) => item.id)
  BaseService.postN('/invw/api/enterApply/batchConfirm', { ids: ids }).then(
    (res: any) => {
      if (res && res.code === 0) {
        ElMessage.success(res.message)
      } else {
        ElMessage.error(res.message)
      }
    }
  )
}
// 关闭弹窗
function handleClose() {
  dialogVisible.value = false
  dialogTitle.value = ''
  typeDialog.value = ''
}
// 表格选中
function selectionChangeHandle(val: any) {
  selectList.value = val
}
const interfaceLowerListArr = ref([]);
onMounted(() => {
  // getStatus();
  // getDeviceModelList();
  // getDeviceTypeList();
  // getManufacturerList();
  getList()
  getLowerList()
})
</script>
<style lang="less" scoped>
.page-home {
  padding: 0 20px;
}

.table-btn {
  margin: 16px 0;
}

.page-wrap {
  display: flex;
  margin-top: 10px;
  justify-content: center;
}

.op-btn {
  padding: 8px;
}

.search-wrap {
  display: flex;
  flex-wrap: wrap;
  align-items: center;

  ::v-deep .el-input,
  ::v-deep .el-date-editor,
  ::v-deep .el-select {
    margin-bottom: 10px;
    margin-right: 10px;
    height: 32px;
  }

  ::v-deep .el-date-editor .el-range-separator {
    width: 20px;
    flex: none;
  }

  ::v-deep .el-input__wrapper {
    flex-grow: 0;
    width: 340px;
  }

  ::v-deep .el-button {
    margin-bottom: 10px;
  }
}

.table-wrap {
  margin: 20px;
}
</style>
