<template>
  <div id="stockManagement_index">
    <el-card shadow="never">
      <el-form :model="formData" ref="formName" label-width="80px">
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="入库时间" prop="time">
              <el-date-picker
                class="w100"
                size="small"
                v-model="formData.time"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="入库单号" prop="bizNo">
              <el-input
                size="small"
                class="w100"
                placeholder="请输入"
                v-model="formData.bizNo"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="入库类型" prop="bizType">
              <el-select
                style="width: 100%"
                filterable
                placeholder="请选择"
                v-model="formData.bizType"
                clearable
              >
                <el-option
                  v-for="item in sceneState"
                  :key="item.code"
                  :value="item.code + ''"
                  :label="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="物品编码" prop="categoryCode">
              <el-input
                size="small"
                class="w100"
                placeholder="请输入"
                v-model="formData.categoryCode"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="物品名称" prop="categoryName">
              <el-input
                size="small"
                class="w100"
                placeholder="请输入"
                v-model="formData.categoryName"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态" prop="status">
              <el-select
                filterable
                size="small"
                class="w100"
                v-model="formData.status"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="item in auditStatus"
                  :key="item.code"
                  :value="item.code"
                  :label="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item label="组织机构:" prop="deptIds">
              <auth-selection
                v-model="formData.deptIds"
                style="width: 100%"
              ></auth-selection>
            </el-form-item>
          </el-col> -->
          <el-col :span="6"  style="height: 42px;">
            <el-form-item label="所属工厂" prop="factoryId">
              <el-select
                filterable
                placeholder="请选择"
                v-model="formData.factoryId"
                clearable
                class="w100"
                @change="getTreeData"
              >
                <el-option
                  v-for="item in factoryList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }"  style="height: 42px;">
            <el-form-item label="仓库名称" prop="warehouseId">
              <el-select
                filterable
                placeholder="请选择"
                v-model="formData.warehouseId"
                clearable
                class="w100"
              >
                <el-option
                  v-for="item in warehouseList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="颜色" prop="colorKey">
              <el-input
                size="small"
                class="w100"
                placeholder="请输入"
                v-model="formData.colorKey"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="型号" prop="modelType">
              <el-input
                size="small"
                class="w100"
                placeholder="请输入"
                v-model="formData.modelType"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col
            style="
              display: flex;
              justify-content: flex-end;
              margin-bottom: 10px;
            "
            :span="6"
          >
            <div>
              <el-button icon="el-icon-refresh-left" size="small" @click="reset"
                >重置</el-button
              >
              <el-button
                type="primary"
                icon="el-icon-search"
                size="small"
                @click="search"
                >搜索</el-button
              >
            </div>
          </el-col>
        </el-row>
      </el-form>

      <ele-pro-table
        ref="table"
        :columns="columns"
        :selection.sync="selection"
        height="calc(100vh-300px)"
        :pageSize="20"
        :datasource="datasource"
        @cell-click="cellClick"
        v-loading="loading"
        :cache-key="cacheKeyUrl"
        @columns-change="handleColumnChange"
      >
        <template v-slot:selection="{ row }">
          <el-radio class="radio" v-model="currentRow.id" :label="row.id"
            ><i></i
          ></el-radio>
        </template>
        <!-- 表头工具栏 -->
        <template v-slot:toolbar>
          <el-button icon="el-icon-plus" type="primary" @click="add"
            >新建</el-button
          >
          <el-button
            icon="el-icon-edit-outline"
            type="primary"
            @click="priceMaintenance"
            v-if="isPrice == 1"
            >单价维护</el-button
          >
          <!-- <el-button icon="el-icon-top" type="primary" @click="shelves"
            >上下架</el-button
          > -->
          <el-button icon="el-icon-receiving" type="primary" @click="outbound"
            >出库</el-button
          >

          <el-dropdown trigger="click" :disabled="selection?.length === 0">
            <el-button type="primary" class="el-icon-printer" size="small">
              打印<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                @click.native="print"
                >打印</el-dropdown-item
              >
              <el-dropdown-item
                v-if="$hasPermission('wms:outin:printIn')"
                @click.native="printkEnter"
                >打印入库单</el-dropdown-item
              >
              <el-dropdown-item
                v-if="$hasPermission('wms:outin:printInHt')"
                @click.native="printkEnterHt"
                >打印入库单</el-dropdown-item
              >
              <el-dropdown-item
                v-if="$hasPermission('wms:outin:printIn1')"
                @click.native="handlePrint('printTemplateTrRef')"
                >打印采购入库单</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>

          <!-- <el-button icon="el-icon-printer" type="primary" @click="print"
            >打印</el-button
          > -->

          <!-- <el-button icon="el-icon-printer" type="primary" @click="printkEnter" v-if="$hasPermission('wms:outin:printIn')"
            >打印入库单</el-button
          > -->

          <!-- <el-button icon="el-icon-printer" type="primary" @click="printkEnterHt" v-if="$hasPermission('wms:outin:printInHt')"
            >打印入库单</el-button
          > -->

          <!-- <el-button icon="el-icon-printer" type="primary" @click="handlePrint('printTemplateTrRef')" v-if="$hasPermission('wms:outin:printIn1')"
            >打印采购入库单</el-button
          > -->

          <!-- <el-button
            icon="el-icon-plus"
            v-if="clientEnvironmentId == 4"
            type="primary"
            @click="exportExcel"
            >导入</el-button
          > -->
        </template>
        <!-- 状态 -->
        <template v-slot:verifyStatus="{ row }">
          <span :class="status[row.verifyStatus]?.class">
            {{ status[row.verifyStatus]?.label }}
          </span>
        </template>
        <!-- 单号链接 -->
        <template v-slot:bizNo="{ row }">
          <el-link type="primary" @click="details(row)">
            {{ row.bizNo }}
          </el-link>
        </template>

        <!-- 操作列 -->
        <template v-slot:action="{ row }">
          <el-link
            type="success"
            :underline="false"
            icon="el-icon-position"
            v-if="row.verifyStatus == 0 || row.verifyStatus == 3"
            @click="submit(row)"
          >
            提交
          </el-link>
          <el-link
            type="primary"
            :underline="false"
            icon="el-icon-view"
            @click="edit(row)"
            v-if="row.verifyStatus == 0 || row.verifyStatus == 3"
          >
            修改
          </el-link>
          <!-- <el-link v-if="row.verifyStatus == 2 && clientEnvironmentId == 3" type="primary" :underline="false"
            icon="el-icon-view" @click="quality(row)">
            质检
          </el-link> -->
          <el-link
            v-if="row.verifyStatus == 2"
            type="primary"
            :underline="false"
            icon="el-icon-sort-up"
            @click="handleShelving(row, 'list')"
          >
            上架
          </el-link>
          <el-link
            v-if="row.verifyStatus == 2"
            type="primary"
            :underline="false"
            icon="el-icon-sort-down"
            @click="handleShelving(row, 'list', 'down')"
          >
            下架
          </el-link>
          <el-link
            type="primary"
            v-if="row.verifyStatus == 0 || row.verifyStatus == 3"
            :underline="false"
            icon="el-icon-delete"
            @click="deleted(row)"
          >
            删除
          </el-link>
        </template>
        <template v-slot:bizType="{ row }">
          {{ handleBizType(row.bizType) }}
        </template>
        <template v-slot:assetType="{ row }">
          {{ handleAssetType(row.extInfo.assetType) }}
        </template>
      </ele-pro-table>
    </el-card>

    <printQRCode ref="printQRCodeRef"></printQRCode>
    <printStockEnter ref="printStockEnterRef" :groupName="groupName"></printStockEnter>
    <printTemplateTr ref="printTemplateTrRef" :groupName="groupName"></printTemplateTr>
    <printStockEnterHt ref="printStockEnterHtRef" :groupName="groupName"></printStockEnterHt>
    <ItemListed ref="itemListedRef" @done="search" />
    <!--  <priceMaintenanceDialog ref="priceMaintenanceDialogRef" /> -->
  </div>
</template>

<script>
  import storageApi from '@/api/warehouseManagement';
  import warehouseDefinition from '@/api/warehouseManagement/warehouseDefinition';
  /*  import priceMaintenanceDialog from './components/priceMaintenanceDialog.vue'; */
  import { allCategoryLevel } from '@/api/classifyManage';
  import { parameterGetByCode } from '@/api/sys/index.js';

  ('@/view/warehouseManagement/stockManagement/components/priceMaintenanceDialog.vue');

  import printQRCode from './components/printQRCode.vue';
  import printStockEnter from './components/printStockEnter.vue';
  import printTemplateTr from './components/print-template-tr.vue';
  import printStockEnterHt from './components/printStockEnterHt.vue';
  import ItemListed from './components/itemListed.vue';
   import tabMixins from '@/mixins/tableColumnsMixin';
  import {
    warehousingType,
    sceneState,
    auditStatus,
    useDict
  } from '@/utils/dict/index';
  import { enterprisePage } from '@/api/bpm/index.js';
  export default {
    mixins: [tabMixins],
    components: { printQRCode, printStockEnter, printTemplateTr, printStockEnterHt, ItemListed },
    data() {
      return {
        cacheKeyUrl: '202606011119-wms-stockManagement-index',
        auditStatus,
        selection: [],
        warehousingType,
        sceneState,
        codeList: [],
        factoryList: [],
        warehouseList: [],
        tableData: [],
        formData: {
          deptIds: '',
          categoryCode: '',
          categoryName: '',
          sourceBizNo: '',
          startTime: '',
          endTime: '',
          status: '',
          factoryId: '',
          time: [],
          warehouseId: '',
          colorKey: '',
          modelType: '',
          bizNo: '', 
          bizType: '',
          // type: 1
        },
        loading: false,
        isPrice: 1,
        total: 0,
        status: [
          { label: '未审核', class: 'ele-text-info' },
          { label: '审核中', class: 'ele-text-primary' },
          { label: '审核通过', class: 'ele-text-success' },
          { label: '驳回', class: 'ele-text-danger' }
        ],
        currentRow: {},
        columns: [
          // {
          //   slot: 'selection',
          //   label: '选择',
          //   width: 50,
          //   align: 'center'
          // },
          {
            width: 45,
            type: 'selection',
            columnKey: 'selection',
            align: 'center'
          },
          {
            type: 'index',
            label: '序号',
            width: 50,
            align: 'center'
          },
          {
            prop: 'bizNo',
            label: '单号',
            align: 'center',
            slot: 'bizNo',
            showOverflowTooltip: true,
            width: 150
          },
          {
            prop: 'warehouseName',
            label: '仓库名称',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 100,
        
          },
          {
            prop: 'bizType',
            slot: 'bizType',
            label: '入库类型',
            align: 'center',
            showOverflowTooltip: true,
            width: 100
          },
          {
            prop: 'assetType',
            slot: 'assetType',
            label: '物品类型',
            align: 'center',
            showOverflowTooltip: true,
            width: 120
          },
          {
            prop: 'categoryNames',
            label: '物品名称',
            align: 'center',
            showOverflowTooltip: true,
            width: 150
          },
          {
            prop: 'categoryCodes',
            label: '物品编码',
            align: 'center',
            showOverflowTooltip: true,
            width: 150
          },
          {
            prop: 'totalQuantity',
            label: '数量',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'specification',
            label: '规格',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'modelType',
            label: '型号',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'colorKey',
            label: '颜色',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'modelKey',
            label: '机型',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'sourceBizNo',
            label: '来源单据',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'createUserName',
            label: '入库人',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            width: 160,
            prop: 'storageTime',
            label: '入库时间',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'verifyName',
            label: '审核人',
            align: 'center',
            showOverflowTooltip: true
          },
          // {
          //   prop: 'startTime',
          //   label: '开始时间',
          //   align: 'center',
          //   showOverflowTooltip: true
          // },
          {
            prop: 'outInStatus',
            label: '入库状态',
            align: 'center',
            showOverflowTooltip: true,
            width: 100,
            formatter: (row, column, cellValue) => {
              if (row.verifyStatus == 2) {
                return row.outInStatus == 1
                  ? '预入库'
                  : row.outInStatus == 2
                  ? '部分入库'
                  : row.outInStatus == 3
                  ? '已入库'
                  : '';
              }
            }
          },
          {
            prop: 'verifyStatus',
            label: '状态',
            align: 'center',
            slot: 'verifyStatus',
            showOverflowTooltip: true,
            width: 100
          },
          {
            columnKey: 'action',
            label: '操作',
            width: 250,
            align: 'center',
            slot: 'action',
            showOverflowTooltip: true
          }
        ],
        groupName:'',
      };
    },
    computed: {
      clientEnvironmentId() {
        return this.$store.state.user.info.clientEnvironmentId;
      },
      // 是否开启响应式布局
      styleResponsive() {
        return this.$store.state.theme.styleResponsive;
      }
    },
    created() {
      //仓库出入库是否显示金额（0：不显示 1：显示）
      parameterGetByCode({
        code: 'wms_price'
      }).then((res) => {
        this.isPrice = res.value;
      });
    },
    mounted() {
      this.getCompanyInfo();
      this.getTypeList();
      this.getFactoryList();
      this.getTreeData();
    },
    methods: {
      getCompanyInfo() {
        enterprisePage({
          pageNum: 1,
          size: 200
        }).then((res) => {
          if (res.list?.length > 0) {
            this.groupName = res.list[0].name;
          }
        });
      },
      async getTreeData() {
        this.formData.warehouseId = '';
        try {
          let res = await storageApi.getWarehouseTrees({
            factoryId: this.formData.factoryId
          });
          if (res?.code === '0') {
            this.warehouseList = res.data;
          }
        } catch (error) {
          console.log(error);
        }
      },
      //获取工厂列表
      async getFactoryList() {
        const res = await warehouseDefinition.getFactoryarea({
          pageNum: 1,
          size: 9999,
          type: 1
        });
        this.factoryList = res.list;
      },
      // 单击获取id
      cellClick(row) {
        this.currentRow = row;
      },
      shelves() {
        console.log('上架');
      },
      handleShelving(row, type, action) {
        this.$refs.itemListedRef.open(row, type, action);
      },
      unShelves() {
        console.log('下架');
      },
      priceMaintenance() {
        if (this.selection.length != 1) {
          return this.$message.error('请选择一条单据');
        } else {
          if (this.selection[0].verifyStatus == 2) {
            this.$router.push({
              path: '/warehouseManagement/stockManagement/priceMaintenance',
              query: {
                ids: this.selection[0].id
              }
            });
            /* this.$refs.priceMaintenanceDialogRef.open(this.selection[0].id); */
          } else {
            this.$message.error('该单据未审核通过');
          }
        }
      },
      async outbound() {
        if (this.selection.length != 1) {
          return this.$message.warning('请选择一条单据');
        } else {
          if (this.selection[0].verifyStatus == 2) {
            const res = await storageApi.getInboundDetailsById(
              this.selection[0].id
            );
            const arr = [];
            for (const key in res.outInDetailList) {
              for (const k in res.outInDetailList[key]
                .outInDetailRecordRequestList) {
                arr.push({
                  ...res.outInDetailList[key].outInDetailRecordRequestList[k]
                });
              }
            }
            let ids = arr.map((item) => item.id).join(',');
            this.$router.push({
              path: '/warehouseManagement/outgoingManagement/add',
              query: {
                ids,
                bizType: this.currentRow.bizType,
                assetType: this.currentRow.extInfo.assetType
              }
            });
          } else {
            this.$message.error('该单据未审核通过');
          }
        }
      },
      handleAssetType(r) {
        let arr = r?.split(',') || [];
        const filteredData = this.codeList.filter((item) =>
          arr.includes(item.dictCode)
        );
        return filteredData.map((item) => item.dictValue).join(',');
      },
      async getTypeList() {
        const { data } = await allCategoryLevel();
        this.codeList = data.map((item) => {
          return { dictCode: item.id, dictValue: item.name };
        });
      },
      submit(row) {
        this.$confirm('此操作将提交流程, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            this.loading = true;
            const data = await storageApi.submitTwo({ outInId: row.id });
            this.loading = false;

            if (data.code == 0) {
              this.$message.success(data.message);
              this.getList();
            }
          })
          .catch(() => {});
      },
      handleBizType(code) {
        for (const key in this.sceneState) {
          if (this.sceneState[key].code == code) {
            return this.sceneState[key].label;
          }
        }
      },
      async datasource({ page, limit, where }) {
        const params = Object.assign({}, this.formData);
        if (params.time?.length) {
          params.startTime = params.time[0];
          params.endTime = params.time[1];
        }
        delete params.time;
        // params.bizStatus = 1;
        const res = await storageApi.getInboundList({
          pageNum: page,
          size: limit,
          type: 1,
          ...params
        });
        return res;
      },
      getAuditStatus: useDict(auditStatus),
      getList() {
        this.$refs.table.reload();
      },
      add(row) {
        const query = {};
        if (row?.id) {
          query.id = row.id;
        }
        this.$router.push({
          path: '/warehouseManagement/stockManagement/add'
          // query
        });
      },
      quality(row) {
        this.$router.push({
          path: '/warehouseManagement/stockManagement/quality',
          query: {
            id: row.id
          }
        });
      },
      exportExcel() {
        this.$router.push({
          path: '/warehouseManagement/stockManagement/add_export'
          // query
        });
      },
      edit(row) {
        this.$router.push({
          path: '/warehouseManagement/stockManagement/add',
          query: {
            detailId: row.id
          }
        });
      },
      details(row) {
        this.$router.push({
          path: '/warehouseManagement/stockManagement/details',
          query: {
            id: row.id,
            verifyStatus: row.verifyStatus
          }
        });
      },
      async deleted(row) {
        this.$confirm('是否确定删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            const data = await storageApi.delete([row.id]);
            if (data.code == '0') {
              this.$message.success('删除成功!');
              this.getList();
            }
          })
          .catch(() => {});
      },
      handleCurrentChange() {
        this.getList();
      },
      handleSizeChange() {
        this.formData.page = 1;
        this.getList();
      },
      search() {
        this.formData.page = 1;
        this.getList();
      },
      reset() {
        this.$refs.formName.resetFields();
        this.search();
      },
      print() {
        if (this.selection.length != 1) {
          return this.$message({
            message: '请先选择一条单据',
            type: 'warning',
            duration: 2000
          });
        }

        if (this.selection[0].verifyStatus !== 2) {
          return this.$message({
            message: '该单据未审核通过',
            type: 'warning',
            duration: 2000
          });
        }

        console.log(this.selection[0]);

        this.$refs.printQRCodeRef.init(this.selection[0].id);

        console.log('print');
      },

      printkEnter() {
        if (this.selection.length != 1) {
          return this.$message({
            message: '请先选择一条单据',
            type: 'warning',
            duration: 2000
          });
        }

        this.$refs.printStockEnterRef.init(this.selection[0].id, this.selection[0]);
      },
      printkEnterHt() {
        if (this.selection.length == 0) {
          return this.$message({
            message: '请先选择单据',
            type: 'warning',
            duration: 2000
          });
        }

        this.$refs.printStockEnterHtRef.init( this.selection.map(item => item.id), this.selection);
      },
      handlePrint(refName) {
        if (this.selection.length != 1) {
          return this.$message({
            message: '请先选择一条单据',
            type: 'warning',
            duration: 2000
          });
        }
        if (this.selection[0].verifyStatus !== 2) {
          return this.$message({
            message: '该单据未审核通过',
            type: 'warning',
            duration: 2000
          });
        }
        this.$refs[refName].init(this.selection[0].id, this.selection[0]);
      }
    }
  };
</script>

<style lang="scss" scoped>
  #stockManagement_index {
    height: calc(100vh - 96px);
    width: 100%;
    padding: 10px;
    box-sizing: border-box;

    // element-ui样式穿透
    :deep(.el-card) {
      height: 100%;

      .el-card__body {
        height: 100%;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;

        .ele-pro-table {
          flex: 1;
          display: flex;
          flex-direction: column;

          .el-table {
            flex: 1;
            // display: flex;
            // flex-direction: column;
            // .el-table__body-wrapper {
            //   flex: 1;
            // }
          }
        }
      }

      .el-form-item {
        margin-bottom: 5px !important;
      }
    }

    .w100 {
      width: 100% !important;
    }

    .p20 {
      padding: 20px;
    }

    .mt20 {
      margin-top: 20px;
    }

    .mt10 {
      margin-top: 10px;
    }

    .el-form {
      overflow: hidden;
    }

    .float-right {
      float: right;
      text-align: right;
      margin-right: 20px;
    }

    .right {
      text-align: right;
    }

    .col {
      color: #aaa;
    }

    .pr10 {
      padding-right: 10px;
    }
  }
</style>
