<template>
  <div>
    <a-card size="small" :bordered="false" class="costSetList-wrap searchBoxNormal">
      <!-- 搜索条件 -->
      <div ref="tableSearch" class="table-page-search-wrapper">
        <a-form layout="inline" id="costSetList-form" @keyup.enter.native="$refs.table.refresh(true)">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-item label="产品编码/原厂编码">
                <a-input id="costSetList-productCode" v-model.trim="queryParam.product.queryWord" allowClear placeholder="请输入产品编码"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="产品名称">
                <a-input id="costSetList-productName" v-model.trim="queryParam.product.name" allowClear placeholder="请输入产品名称"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="审核状态">
                <v-select
                  v-model="queryParam.auditState"
                  ref="auditState"
                  id="costSetList-auditState"
                  code="SUPPLIER_PRODUCT_STATE"
                  placeholder="请选择审核状态"
                  allowClear></v-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="品牌">
                <ProductBrand id="costSeting-productBrandSn" v-model="queryParam.product.productBrandSn"></ProductBrand>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="产品分类">
                <ProductType id="costSeting-productType" v-model="productType" @change="changeProductType"></ProductType>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="供应商名称">
                <a-input id="costSetList-productName" v-model.trim="queryParam.supplierName" allowClear placeholder="请输入供应商名称"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
              <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="costSetList-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="costSetList-reset">重置</a-button>
              <a-button
                style="margin-left: 10px"
                type="primary"
                class="button-warning"
                @click="handleExport"
                :disabled="disabled"
                :loading="exportLoading"
                v-if="$hasPermissions('B_costSetExportDetail')"
                id="costSeting-export">导出明细</a-button>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card size="small" :bordered="false">
      <a-spin :spinning="spinning" tip="Loading...">
        <!-- 操作按钮 -->
        <div class="table-operator">
          <a-button id="costSeting-new" type="primary" v-if="$hasPermissions('B_costSetAddProduct')" @click="newProduct=true">新增</a-button>
          <a-button id="costSeting-import" type="primary" v-if="$hasPermissions('B_costSetBatchImport')" class="button-warning" @click="handleBatchImport">批量导入</a-button>
          <a-button id="costSeting-paudit" type="primary" ghost v-if="$hasPermissions('B_costSetAudit')" @click="handleBatchAudit">批量审核</a-button>
        </div>
        <!-- 列表 -->
        <s-table
          class="sTable fixPagination"
          ref="table"
          id="costSeting-table"
          :style="{ height: tableHeight+70+'px' }"
          size="small"
          :rowKey="(record) => record.supplierProductSn"
          rowKeyName="supplierProductSn"
          :row-selection="$hasPermissions('B_costSetAudit')?{ columnWidth: 40, getCheckboxProps: record => ({ props: { disabled: record.auditState!=='WAIT' } }) }:null"
          @rowSelection="rowSelectionFun"
          :columns="columns"
          :data="loadData"
          :pageSize="30"
          :scroll="{ y: tableHeight }"
          :defaultLoadData="false"
          bordered>
          <!-- 产品分类 -->
          <template slot="productType" slot-scope="text, record">
            <span v-if="record.product&&(record.product.productTypeName2 || record.product.productTypeName3)">{{ record.product.productTypeName2 }} {{ record.product.productTypeName3 ? '>' : '' }} {{ record.product.productTypeName3 }}</span>
            <span v-else>--</span>
          </template>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <div>
              <a-button
                :id="'costSetList-audit-'+record.id"
                size="small"
                type="link"
                class="button-warning"
                v-if="record.auditState=='WAIT'&&$hasPermissions('B_costSetAudit')"
                @click="handleAudit([record.supplierProductSn])"
              >审核</a-button>
              <a-button
                :id="'costSetList-editcost-'+record.id"
                size="small"
                type="link"
                class="button-warning"
                v-if="record.auditState=='WAIT'&&$hasPermissions('B_costSetting')"
                @click="handleCostSet(record,editFlag = true)"
              >编辑成本</a-button>
              <a-button
                :id="'costSetList-setcost-'+record.id"
                size="small"
                type="link"
                class="button-warning"
                v-if="record.auditState!='WAIT'&&$hasPermissions('B_costSetting')"
                @click="handleCostSet(record,false)"
              >设置成本</a-button>
            </div>
          </template>
        </s-table>
      </a-spin>

      <!-- 新增 -->
      <addProductModal :openModal="newProduct" @close="newProduct=false" @ok="handleProductsOk" />
      <!-- 设置成本价 -->
      <SettingCost ref="settingCost" :edit="editFlag" :openModal="openSetModal" @ok="$refs.table.refresh()" @close="openSetModal=false"></SettingCost>
      <!-- 导入产品 -->
      <importGuideModal :openModal="openGuideModal" @close="openGuideModal=false" @ok="handleGuideOk" />
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
// 组件
import { STable, VSelect } from '@/components'
import { hdExportExcel } from '@/libs/exportExcel'
import ProductType from '@/views/common/productType.js'
import ProductBrand from '@/views/common/productBrand.js'
import addProductModal from './addProductModal.vue'
import ImportGuideModal from './importGuideModal.vue'
import SettingCost from './settingCost.vue'
// 接口
import { supplierProductList, supplierProductExportDetail, supplierProductUpdateAuditState, supplierProductNewBatchInsert } from '@/api/supplier'
export default {
  name: 'CostSettingList',
  mixins: [commonMixin],
  components: { STable, VSelect, ProductBrand, ProductType, addProductModal, SettingCost, ImportGuideModal },
  data () {
    return {
      spinning: false,
      exportLoading: false, // 导出按钮加载状态
      disabled: false, //  查询、重置按钮是否可操作
      advanced: true, // 高级搜索 展开/关闭
      openGuideModal: false, // 导入指导弹窗
      tableHeight: 0, // 表格高度
      //  查询条件
      queryParam: {
        supplierName: '', // 供应商名称
        product: {
          name: '', //  产品名称
          queryWord: '', // 产品编码/原厂编码
          productBrandSn: undefined, //  产品品牌
          productTypeSn1: '', //  产品一级分类
          productTypeSn2: '', //  产品二级分类
          productTypeSn3: '' //  产品三级分类
        },
        auditState: undefined // 审核状态
      },
      productType: [], // 产品分类
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        // 获取列表数据
        return supplierProductList(Object.assign(parameter, this.queryParam)).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            // 计算表格显示序号
            const no = (data.pageNo - 1) * data.pageSize
            for (var i = 0; i < data.list.length; i++) {
              data.list[i].no = no + i + 1
            }
            this.disabled = false
          }
          this.spinning = false
          return data
        })
      },
      rowSelectionInfo: null, // 已选数据
      newProduct: false, // 新增弹框
      openSetModal: false, // 设置弹框
      editFlag: false // 是否编辑
    }
  },
  computed: {
    columns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '产品名称', dataIndex: 'product.name', width: '12%', align: 'left', customRender: function (text) { return text || '--' } },
        { title: '产品编码', dataIndex: 'product.code', width: '8%', align: 'left', customRender: function (text) { return text || '--' } },
        { title: '原厂编码', dataIndex: 'product.origCode', width: '8%', align: 'left', customRender: function (text) { return text || '--' } },
        { title: '产品品牌', dataIndex: 'product.productBrandName', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品分类', scopedSlots: { customRender: 'productType' }, width: '12%', align: 'left' },
        { title: '供应商名称', dataIndex: 'supplierName', width: '12%', align: 'left', customRender: function (text) { return text || '--' } },
        { title: '审核时间', dataIndex: 'auditTime', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '审核状态', dataIndex: 'auditStateDictValue', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '8%', align: 'center' }
      ]

      arr.splice(7, 0, { title: '当前成本价', dataIndex: 'cost', width: '7%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      arr.splice(8, 0, { title: '变更成本价', dataIndex: 'modifyCost', width: '7%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      return arr
    }
  },
  methods: {
    // 表格选中项
    rowSelectionFun (obj) {
      this.rowSelectionInfo = obj || null
    },
    // 批量导入产品
    handleGuideOk (obj) {
      supplierProductNewBatchInsert(obj).then(res => {
        if (res.status == 200) {
          this.$refs.table.refresh(true)
        }
      })
    },
    //  重置
    resetSearchForm () {
      this.queryParam.supplierName = ''
      this.queryParam.product.name = ''
      this.queryParam.product.queryWord = ''
      this.queryParam.product.productBrandSn = undefined
      this.queryParam.product.productTypeSn1 = ''
      this.queryParam.product.productTypeSn2 = ''
      this.queryParam.product.productTypeSn3 = ''
      this.queryParam.auditState = undefined
      this.productType = []
      this.$refs.table.refresh(true)
    },
    //  选择产品分类  change
    changeProductType (val, opt) {
      this.queryParam.product.productTypeSn1 = val[0] ? val[0] : ''
      this.queryParam.product.productTypeSn2 = val[1] ? val[1] : ''
      this.queryParam.product.productTypeSn3 = val[2] ? val[2] : ''
    },
    // 导出明细
    handleExport () {
      const _this = this
      const params = _this.queryParam
      _this.exportLoading = true
      _this.spinning = true
      hdExportExcel(supplierProductExportDetail, params, '成本设置明细', function () {
        _this.exportLoading = false
        _this.spinning = false
      })
    },
    // 新增成功
    handleProductsOk () {
      this.newProduct = false
      this.resetSearchForm()
    },
    // 批量导入
    handleBatchImport () {
      this.openGuideModal = true
    },
    // 批量审核
    handleBatchAudit () {
      const row = this.rowSelectionInfo && this.rowSelectionInfo.selectedRowKeys
      if (!this.rowSelectionInfo || (row.length < 1)) {
        this.$message.warning('请在列表中进行勾选！')
        return false
      }
      this.handleAudit(row)
    },
    // 单个审核
    handleAudit (sn) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要审核通过吗？',
        centered: true,
        closable: true,
        okText: '通过',
        cancelText: '不通过',
        onOk () {
          _this.auditOrder(sn, 'PASS')
        },
        onCancel (e) {
          if (!e.triggerCancel) {
            _this.auditOrder(sn, 'REJECT')
          }
          _this.$destroyAll()
        }
      })
    },
    // 提交审核
    auditOrder (sn, val) {
      this.spinning = true
      supplierProductUpdateAuditState({
        auditState: val,
        supplierProductSnList: sn
      }).then(res => {
        if (res.status == 200) {
          this.$refs.table.refresh(true)
          this.$refs.table.clearSelected()
          this.$message.info(res.message)
        }
        this.spinning = false
      })
    },
    // 成本设置
    handleCostSet (row, flag) {
      this.openSetModal = true
      this.editFlag = !!flag
      this.$refs.settingCost.setData(row)
    },
    // 页面初始化
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 240
    }
  },
  watch: {
    // 展开关闭  监听表格高度变化
    advanced (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
      this.resetSearchForm()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
      this.resetSearchForm()
    }
    // 仅刷新列表，不重置页面
    if (this.$store.state.app.updateList) {
      this.pageInit()
      this.$refs.table.refresh()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
