<template>
  <div class="app-container calendar-list-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-date-picker v-model="listQuery.startDate" value-format="yyyy-MM-dd" type="date" placeholder="开始日期"
      class="filter-item" style="width:200px">
      </el-date-picker>
      <el-date-picker v-model="listQuery.endDate" value-format="yyyy-MM-dd" type="date" placeholder="结束日期"
      class="filter-item" style="width:200px">
      </el-date-picker>
      <treeselect class="filter-item" default-expand-all v-model="listQuery.requireDepartmentId" :options="deptOptions"
                :normalizer="normalizer" placeholder="出库部门" style="width: 200px" />
      <el-select v-model="listQuery.storeId" clearable placeholder="门店" class="filter-item" style="width: 200px">
        <el-option :key="item.id" v-for="item in storeList" :label="item.storeName" :value="item.id">
        </el-option>
      </el-select>
      <el-select v-model="listQuery.warehouseId" clearable filterable placeholder="仓库" class="filter-item" style="width: 200px">
        <el-option :key="item.id" v-for="item in warehouseList" :label="item.warehouseName" :value="item.id">
        </el-option>
      </el-select>
      
      <el-select v-model="listQuery.isRunFinish" clearable placeholder="发货状态" class="filter-item" style="width: 200px">
        <el-option :key="item.type" v-for="item in typeList" :label="item.name" :value="item.type">
        </el-option>
      </el-select>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button class="filter-item" v-waves icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      <el-button class="filter-item" type="primary" @click="handleCreate" icon="el-icon-plus">添加</el-button>
      <el-button class="filter-item" v-waves icon="el-icon-download"
        @click="handleDownload">导出</el-button>
      <!-- <el-button class="filter-item" type="success" icon="el-icon-takeaway-box" @click="executeAll">批量发货</el-button> -->
      <el-button class="filter-item" type="warning" icon="el-icon-delete" @click="delAll">批量删除</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table size="small" :data="list" @selection-change="handleSelectionChange" v-loading="listLoading"
      element-loading-text="正在查询中。。。" border fit highlight-current-row>
      <el-table-column type="selection" width="55px" align="center"> </el-table-column>
      <el-table-column type="index" label="序号" header-align="center" align="center">
      </el-table-column>
      <el-table-column align="center" min-width="150px" label="出库单号">
        <template slot-scope="scope">
          <router-link :to="{ name: 'retrievalDetail', params: { id: scope.row.id } }">
            <div style="color: #337ab7;cursor: pointer;">{{ scope.row.serialCode }}</div>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column align="center" min-width="100px" label="出库时间" prop="serialDate">
      </el-table-column>
      <el-table-column align="center" min-width="100px" label="出库部门" prop="requireDepartmentName">
      </el-table-column>
      <el-table-column align="center" min-width="100px" label="门店" prop="storeName">
      </el-table-column>
      <el-table-column align="center" min-width="100px" label="仓库" prop="warehouseName">
      </el-table-column>
      <el-table-column align="center" min-width="100px" label="经手人" prop="outHandlerName">
      </el-table-column>
      <el-table-column align="center" min-width="100px" label="发货状态">
        <template slot-scope="props">
            <span v-if="props.row.isRunFinish == '0'" style="color: #67C23A;font-weight: bold;">已发货</span>
            <span v-if="props.row.isRunFinish == '1'" style="color: #E6A23C;font-weight: bold;">待发货</span>
            <span v-if="props.row.isRunFinish == '2'" style="color: #E6A23C;font-weight: bold;">已作废</span>
          </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="240px" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.isRunFinish == '1'" type="success" size="small" @click="handleExecute(scope.row)">发货</el-button>
          <el-button v-if="scope.row.isRunFinish == '1'" type="primary" size="small" @click="handleUpdate(scope.row)">编辑</el-button>
           <el-button v-if="scope.row.isRunFinish != '0'" type="danger" size="small"
            @click="handleDelete(scope.row)">删除</el-button>
          <el-button v-if="scope.row.isRunFinish == '0'" type="warning" size="small"
            @click="handleCancelShow(scope.row.id)">作废</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="listQuery.page" :page-sizes="[10, 20, 30, 50]" :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <!-- 作废原因对话框 -->
    <el-dialog :close-on-click-modal="false" title="单据作废" :visible.sync="dialogFormVisible" width="40%">
      <el-form :rules="rules" ref="dataForm" :model="dataForm" status-icon label-position="left" label-width="80px">
        <el-form-item label="作废原因" prop="cancelMsg">
          <el-input type="textarea" :rows="2" placeholder="请输入作废原因" v-model="dataForm.cancelMsg"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCancel()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { listRetrieval, deleteRetrieval, executeRetrieval,cancelRetrieval } from "@/api/retrieval";
import { storeList } from "@/api/store";
import { warehouseList } from "@/api/warehouse";
import { listDept } from "@/api/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import waves from "@/directive/waves"; // 水波纹指令

export default {
  components: { Treeselect },
  directives: { waves },
  data() {
    return {
      cancelId: '',
      dialogFormVisible: false,
      dataForm: {
        cancelMsg: ''
      },
      rules: {
        cancelMsg: [{ required: true, message: "作废原因不能为空", trigger: "blur" }],
      },
      // 树选项
      deptOptions: [],
      storeList: [],
      warehouseList: [],
      typeList: [
        {
          type: '0',
          name: "已发货",
        },
        {
          type: '1',
          name: "待发货",
        },
         {
          type: '2',
          name: "已作废",
        },
      ],
      list: [

      ],
      delarr: [],
      multipleSelection: [],
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 10,
        startDate: '',
        endDate: '',
        responsibleDept: undefined,
        storeId: '',
        warehouseId: '',
        isRunFinish: '',
      },
    }
  },
  created() {
    this.getStoreList();
    this.getWarehouseList();
    this.getList();
    this.getListDept();
  },
  methods: {
    handleCancelShow(id) {
      this.dialogFormVisible = true;
      this.cancelId = id;
      this.$nextTick(() => {
        this.dataForm.cancelMsg = '';
        this.$refs["dataForm"].clearValidate();
      });
    },
    handleCancel() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          cancelRetrieval({ id: this.cancelId, cancelMsg: this.dataForm.cancelMsg }).then(() => {
            this.dialogFormVisible = false;
            this.$notify({
              title: "成功",
              message: "操作成功",
              type: "success",
              duration: 2000,
            });
            this.getList();
          });
        }
      })

    },
    getListDept() {
            listDept().then(response => {
                this.deptOptions = this.handleTree(response.data.data, "deptId");
            });
        },
        /** 转换部门数据结构 */
        normalizer(node) {
            if (node.children && !node.children.length) {
                delete node.children;
            }
            return {
                id: node.deptId,
                label: node.deptName,
                children: node.children
            };
        },
    /** 获取仓库列表数据 */
    getStoreList() {
      storeList().then(response => {
        this.storeList = response.data.data;
      }).catch(() => { });
    },
    /** 获取仓库列表数据 */
    getWarehouseList() {
      warehouseList().then(response => {
        this.warehouseList = response.data.data;
      }).catch(() => { });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.listQuery = {
        page: 1,
        limit: 10,
        page: 1,
        limit: 10,
        startDate: '',
        endDate: '',
        responsibleDept: undefined,
        storeId: '',
        warehouseId: '',
        isRunFinish: '',
      },
        this.getList()
    },
    handleDownload() {
      window.location.href = process.env.BASE_API + '/warehouse-out/export';
    },
    handleCreate() {
      this.$router.push({
        name: 'retrievalAdd',
        // params: { callback: this.getList }
      })
    },
    getList() {
      this.listLoading = true
      listRetrieval(this.listQuery).then(response => {
        this.list = response.data.data.items
        this.total = response.data.data.total
        this.listLoading = false
      }).catch(() => {
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },

    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },

    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },

    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },

    handleUpdate(row) {
      this.$router.push({
        name: 'retrievalEdit',
        params: { id: row.id }
      })
    },
    handleExecute(row) {
      this.$confirm('确认发货吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        executeRetrieval({ ids: row.id }).then(response => {
          this.$notify({
            title: '成功',
            message: '发货成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      }).catch(() => { })
    },
    executeAll() {
      const length = this.multipleSelection.length;
      if (length > 0) {
        this.$confirm("确认发货吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          for (let i = 0; i < length; i++) {
            this.delarr.push(this.multipleSelection[i].id);
          }
          const ids = this.delarr.join(",");
          executeRetrieval({ ids: ids }).then(() => {
            this.$notify({
              title: "成功",
              message: "发货成功",
              type: "success",
              duration: 2000,
            });
            this.getList();
          })
        })
      } else {
        this.$notify({
          title: "提示",
          message: "请选择要发货的信息！",
          type: "warning",
        });
      }
    },
    handleDelete(row) {
      this.$confirm('确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRetrieval({ ids: row.id }).then(response => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      }).catch(() => { })
    },
    delAll() {
      const length = this.multipleSelection.length;
      if (length > 0) {
        this.$confirm("确认删除吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          for (let i = 0; i < length; i++) {
            this.delarr.push(this.multipleSelection[i].id);
          }
          const ids = this.delarr.join(",");
          deleteRetrieval({ ids: ids }).then(() => {
            this.$notify({
              title: "成功",
              message: "删除成功",
              type: "success",
              duration: 2000,
            });
            this.getList();
          })
        })
      } else {
        this.$notify({
          title: "提示",
          message: "请选择要删除的信息！",
          type: "warning",
        });
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
  }
}
</script>