<template>
  <div>
    <en-table-layout :tableData="tableData.data" :loading="loading" @selection-change="handleSelectionChange">
      <div slot="toolbar" class="inner-toolbar">
        <div class="toolbar-btns">
          <el-button size="mini" v-if="checkPermission(['supplierReturns:add'])" type="primary"
            @click="handleAddPurchasePlan">新增</el-button>
          <el-button size="mini" v-if="checkPermission(['supplierReturns:del'])" type="danger"
            @click="handleDeletePurchasePlan" :disabled="multipleSelection.length === 0">删除</el-button>
        </div>
        <div class="toolbar-search">
          <en-table-search @search="searchEvent" @advancedSearch="advancedSearchEvent" placeholder="请输入退货单编号" advanced
            advancedWidth="465">
            <template slot="advanced-content">
              <el-form ref="advancedForm" :model="advancedForm" label-width="90px">
                <el-form-item label="所属部门">
                  <el-cascader v-model="advancedForm.dept_id" :options="deptList" :props="{
                    label: 'name',
                    value: 'id',
                    emitPath: false,
                    checkStrictly: true
                  }" clearable></el-cascader>
                </el-form-item>
                <el-form-item label="供应商">
                  <el-select v-model="advancedForm.supplier_id">
                    <el-option v-for="item in supplierList" :key="item.id" :label="item.custom_name" :value="item.id" />
                  </el-select>
                </el-form-item>
                <el-form-item label="时间">
                  <el-date-picker v-model="advancedForm.purchasePlan_time_range" type="daterange" align="center"
                    :editable="false" unlink-panels :clearable="true" :default-time="['00:00:00', '23:59:59']"
                    range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" value-format="timestamp"
                    :picker-options="{ disabledDate(time) { return time.getTime() - 1 >= new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()).getTime() + 86400000 - 1 }, shortcuts: MixinPickerShortcuts }">
                  </el-date-picker>
                </el-form-item>
              </el-form>
            </template>
          </en-table-search>
        </div>
      </div>

      <template slot="table-columns">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="sn" label="退货单编号">
          <template slot-scope="scope">
            <router-link
              v-if="checkPermission(['supplierReturns'])"
              style="color: #409eff;"
              :to="{ name: 'supplierReturnsDetail', params: { id: scope.row.id } }">
              {{ scope.row.sn }}
            </router-link>
            <span v-else>{{scope.row.sn}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="退货日期">
          <template slot-scope="scope">{{ scope.row.return_time | unixToDate }}</template>
        </el-table-column>
        <el-table-column prop="dept_name" label="所属部门" />
        <el-table-column prop="warehouse_name" label="仓库" />
        <el-table-column prop="supplier_name" label="供应商" />
        <el-table-column prop="warehouse_entry_sn" label="对应入库单编号" />
        <el-table-column prop="handle_by_name" label="经手人" />
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">{{ statusFilter(scope.row.status) }}</template>
        </el-table-column>
        <el-table-column prop="audit_by" label="审核人" />
        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <el-button type="success" size="mini"
              v-if="scope.row.allowable.submit && checkPermission(['supplierReturns:submit'])"
              @click="handleSubmitPurchasePlan(scope.row)">提交</el-button>
            <el-button type="danger" size="mini"
              v-else-if="scope.row.allowable.withdraw && checkPermission(['supplierReturns:withdraw'])"
              @click="handleWithdrawPurchasePlan(scope.row)">撤回</el-button>
            <el-button type="success" size="mini"
              v-if="scope.row.allowable.audit && checkPermission(['supplierReturns:audit'])"
              @click="handleAuditPurchasePlan(scope.row)">审核</el-button>
            <el-button size="mini" v-if="scope.row.allowable.edit && checkPermission(['supplierReturns:edit'])"
              @click="handleEditPurchasePlan(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </template>

      <el-pagination v-if="tableData" slot="pagination" @size-change="handlePageSizeChange"
        @current-change="handlePageCurrentChange" :current-page="tableData.page_no" :page-sizes="[10, 20, 50, 100]"
        :page-size="tableData.page_size" layout="total, sizes, prev, pager, next, jumper" :total="tableData.data_total">
      </el-pagination>
    </en-table-layout>
  </div>
</template>

<script>
import * as API_Supplier from '@/api/supplier'
import { Foundation } from '~/ui-utils'
import * as API_Setting from '@/api/setting'
import * as API_BasicSetting from '@/api/basicSetting'
export default {
  name: 'supplierReturns',
  data() {
    return {
      supplierList: [],
      deptList: [],
      multipleSelection: [],
      // 列表loading状态
      loading: false,
      // 列表参数
      params: {
        page_no: 1,
        page_size: 10
      },
      // 高级搜索数据
      advancedForm: {},
      // 列表数据
      tableData: ''
    }
  },
  mounted() {
    this.GET_supplierReturnsList()
    this.GET_DeptList()
    this.GET_SupplierList()
  },
  watch: {
    $route: function({ query }) {
      this.params.page_no = 1
      this.GET_supplierReturnsList()
    }
  },
  methods: {
    /** 获取供应商 */
    GET_SupplierList() {
      API_BasicSetting.getSupplierListAll().then(response => {
        this.supplierList = response
      })
    },
    /** 获取部门 */
    GET_DeptList() {
      API_Setting.getDeptList().then(response => {
        this.deptList = Foundation.buildTree(response, '0')
      })
    },
    statusFilter(val) {
      switch (val) {
        case 'NotSubmit':
          return '未提交'
        case 'Submit':
          return '已提交'
        case 'AuditPass':
          return '审核通过'
        case 'AuditReject ':
          return '审核驳回'
        default:
          return ''
      }
    },
    /** 多选改变 */
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size
      this.GET_supplierReturnsList()
    },

    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page
      this.GET_supplierReturnsList()
    },
    handleEditPurchasePlan(row) {
      this.$router.push({
        name: 'supplierReturnsEdit',
        params: { id: row.id }
      })
    },
    /** 添加供应商退货 */
    handleAddPurchasePlan() {
      this.$router.push({
        name: 'supplierReturnsAdd',
        params: { callback: this.GET_supplierReturnsList }
      })
    },
    handleAuditPurchasePlan(row) {
      this.$router.push({
        name: 'supplierReturnsAudit',
        params: { id: row.id }
      })
    },
    handleWithdrawPurchasePlan(row) {
      this.$confirm('确定要撤回这个供应商退货吗？', '提示', { type: 'warning' }).then(() => {
        API_Supplier.withdrawsupplierReturns(row.id).then(() => {
          this.$message.success('撤回成功！')
          this.GET_supplierReturnsList()
        })
      }).catch(() => { })
    },
    handleSubmitPurchasePlan(row) {
      this.$confirm('确定要提交这个供应商退货吗？', '提示', { type: 'warning' }).then(() => {
        API_Supplier.submitsupplierReturns(row.id).then(() => {
          this.$message.success('提交成功！')
          this.GET_supplierReturnsList()
        })
      }).catch(() => { })
    },
    /** 删除供应商退货 */
    handleDeletePurchasePlan() {
      if (!this.multipleSelection || !this.multipleSelection.length) return this.$message.error('请先选择！')
      this.$confirm('确定要删除这些供应商退货吗？', '提示', { type: 'warning' }).then(() => {
        const ids = this.multipleSelection.map(item => item.id)
        API_Supplier.deletesupplierReturns(ids).then(() => {
          this.$message.success('删除成功！')
          this.GET_supplierReturnsList()
        })
      }).catch(() => { })
    },
    /** 搜索事件触发 */
    searchEvent(data) {
      this.params = {
        ...this.params,
        sn: data
      }
      Object.keys(this.advancedForm).forEach((key) => delete this.params[key])
      this.params.page_no = 1
      this.GET_supplierReturnsList()
    },
    /** 高级搜索事件触发 */
    advancedSearchEvent() {
      this.params = {
        ...this.params,
        ...this.advancedForm
      }
      delete this.params.start_time
      delete this.params.end_time
      if (this.advancedForm.purchasePlan_time_range) {
        this.params.start_time = parseInt(Number(this.advancedForm.purchasePlan_time_range[0]) / 1000)
        this.params.end_time = parseInt(Number(this.advancedForm.purchasePlan_time_range[1]) / 1000)
      }
      delete this.params.purchasePlan_time_range
      this.params.page_no = 1
      this.GET_supplierReturnsList()
    },

    /** 获取供应商退货列表 */
    GET_supplierReturnsList() {
      this.loading = true
      API_Supplier.getsupplierReturnsList(this.params).then(response => {
        this.loading = false
        this.tableData = response
      }).catch(() => { this.loading = false })
    }
  }
}
</script>

<style type="text/scss" lang="scss" scoped>
.print {
  margin-left: 790px;
}

.tips-t {
  display: flex;
  padding: 10px 0;

  div {
    flex: 1;
    text-align: center;
  }
}

.tips-f {
  padding: 20px 0;
}

.face-image {
  display: block;
  width: 50px;
  height: 50px;
  margin: 0 auto;
}

/deep/ .el-dialog__body {
  padding: 10px 20px;
}
</style>
