<template>
  <a-card size="small" :bordered="false" class="productInfoList-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 搜索条件 -->
      <div class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="$refs.table.refresh(true)">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-item label="产品名称">
                <a-input id="productInfoList-name" v-model.trim="queryParam.name" allowClear placeholder="请输入产品名称"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="产品编码/原厂编码">
                <a-input id="productInfoList-queryWord" v-model.trim="queryParam.queryWord" allowClear placeholder="请输入产品编码/原厂编码"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="品牌">
                <a-select
                  placeholder="请选择"
                  id="productInfoList-productBrandSn"
                  allowClear
                  v-model="queryParam.productBrandSn"
                  :showSearch="true"
                  option-filter-prop="children"
                  :filter-option="filterOption">
                  <a-select-option v-for="item in productBrandList" :key="item.brandSn" :value="item.brandSn">{{ item.brandName }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="产品分类">
                  <a-cascader
                    @change="changeProductType"
                    expand-trigger="hover"
                    change-on-select
                    :options="productTypeList"
                    :fieldNames="{ label: 'productTypeName', value: 'productTypeSn', children: 'children' }"
                    id="productInfoList-productType"
                    placeholder="请选择产品分类"
                    allowClear
                    v-model="productType" />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="产品状态">
                  <v-select code="PRODUCT_STATUS" id="productInfoList-state" v-model="queryParam.state" allowClear placeholder="请选择产品状态"></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="定价状态">
                  <v-select code="PRICING_STATUS" id="productInfoList-pricingState" v-model="queryParam.pricingState" allowClear placeholder="请选择定价状态"></v-select>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24">
              <a-button style="margin-bottom: 18px;" type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="productInfoList-refresh">查询</a-button>
              <a-button style="margin: 0 0 18px 5px" @click="resetSearchForm" :disabled="disabled" id="productInfoList-reset">重置</a-button>
              <a-button
                v-if="$hasPermissions('B_productInfo_export')"
                style="margin-left: 5px"
                type="primary"
                class="button-warning"
                @click="handleExport"
                :disabled="disabled"
                :loading="exportLoading"
                id="productInfoList-export">导出</a-button>
              <a @click="advanced=!advanced" style="margin-left: 8px">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'"/>
              </a>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- 操作按钮 -->
      <div class="table-operator">
        <a-button id="productInfoList-add" type="primary" v-if="$hasPermissions('B_productInfo_add')" class="button-error" @click="handleEdit()">新增</a-button>
        <a-button
          id="productInfoList-batchAudit"
          type="primary"
          v-if="$hasPermissions('B_productInfo_batchAudit')"
          class="button-warning"
          :loading="loadingAudit"
          @click="handleBatchAudit"
          style="margin: 0 15px;">批量审核</a-button>
        <a-button
          id="productInfoList-batchLaunch"
          type="primary"
          v-if="$hasPermissions('B_productInfo_batchLaunch')"
          class="button-primary"
          :loading="loadingLaunch"
          @click="handleBatchLaunch"
          style="margin: 0 15px;">批量上线</a-button>
        <a-button
          id="productInfoList-batchDownline"
          type="primary"
          v-if="$hasPermissions('B_productInfo_batchDownline')"
          class="button-grey"
          :loading="loadingDownline"
          @click="handleBatchDownline"
          style="margin: 0 15px;">批量下线</a-button>
        <span style="margin-left: 8px" v-if="$hasPermissions('B_productInfo_batchAudit') || $hasPermissions('B_productInfo_batchLaunch') || $hasPermissions('B_productInfo_batchDownline')">
          <template v-if="hasSelected">{{ `已选 ${selectedRowKeys.length} 项` }}</template>
        </span>
      </div>
      <s-table
        class="sTable"
        ref="table"
        size="default"
        :row-selection=" showSelect ?{ selectedRowKeys: selectedRowKeys, onChange: onChange, onSelect: onSelectChange, onSelectAll: onSelectAllChange }:null"
        :rowKey="(record) => record.id"
        :columns="columns"
        :data="loadData"
        :scroll="{ x: 2150, y: tableHeight }"
        bordered>
        <!-- 自定义表头 -->
        <template slot="arrowFalgTitle">
          <a-tooltip placement="top">
            <template slot="title">
              <span>自有即箭冠产品，非自有即非箭冠产品</span>
            </template>
            自有<a-icon type="question-circle" :style="{ marginLeft: '10px' }" />
          </a-tooltip>
        </template>
        <template slot="arrowFalg" slot-scope="text, record">
          <span v-if="record.arrowFalg">{{ record.arrowFalg == 1 ? '是' : '否' }}</span>
          <span v-else>--</span>
        </template>
        <!-- 产品分类 -->
        <template slot="productType" slot-scope="text, record">
          <span v-if="record.productTypeName2 || record.productTypeName3">{{ record.productTypeName2 }} {{ record.productTypeName3 ? '>' : '' }} {{ record.productTypeName3 }}</span>
          <span v-else>--</span>
        </template>
        <!-- 定价状态 -->
        <template slot="pricingState" slot-scope="text, record">
          <a-badge :color="record.pricingState=='WAIT_PRICING'?'gold':record.pricingState=='WAIT_PRICING_AUDIT'?'volcano':'#87d068'" :text="record.pricingStateDictValue" />
        </template>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <a-button
            size="small"
            type="link"
            v-if="record.state=='WAIT' && $hasPermissions('B_productInfo_audit')"
            class="button-warning"
            @click="handleAudit(record)"
            id="productInfoList-audit-btn">审核</a-button>
          <a-button
            size="small"
            type="link"
            v-if="(record.state=='WAIT_ONLINE'||record.state=='OFFLINE') && $hasPermissions('B_productInfo_launch')"
            class="button-primary"
            @click="handleLaunch(record)"
            id="productInfoList-launch-btn">上线</a-button>
          <a-button
            size="small"
            type="link"
            v-if="record.state=='ONLINE' && $hasPermissions('B_productInfo_downline')"
            class="button-grey"
            @click="handleDownline(record)"
            id="productInfoList-downline-btn">下线</a-button>
          <a-button
            size="small"
            type="link"
            v-if="$hasPermissions('B_productInfo_edit')"
            class="button-info"
            @click="handleEdit(record)"
            id="productInfoList-edit-btn">编辑</a-button>
          <a-button
            size="small"
            type="link"
            v-if="$hasPermissions('B_productInfo_detail')"
            class="button-success"
            @click="handleDetail(record)"
            id="productInfoList-detail-btn">详情</a-button>
          <a-button
            size="small"
            type="link"
            v-if="record.state=='WAIT' && $hasPermissions('B_productInfo_del')"
            class="button-error"
            @click="handleDel(record)"
            id="productInfoList-del-btn">删除</a-button>
          <span v-if="!(record.state=='WAIT' && $hasPermissions('B_productInfo_audit')) && !((record.state=='WAIT_ONLINE'||record.state=='OFFLINE') && $hasPermissions('B_productInfo_launch')) && !(record.state=='ONLINE' && $hasPermissions('B_productInfo_downline')) && !$hasPermissions('B_productInfo_edit') && !$hasPermissions('B_productInfo_detail') && !(record.state=='WAIT' && $hasPermissions('B_productInfo_del'))">--</span>
        </template>
      </s-table>
    </a-spin>
    <!-- 产品详情 -->
    <product-info-detail-modal :openModal="openModal" :itemSn="itemSn" @close="closeModal" />
    <!-- 产品下线 -->
    <product-info-offline-modal :openModal="openOfflineModal" :offlineProductList="offlineProductList" @close="closeOfflineModal" @ok="$refs.table.refresh()" />
  </a-card>
</template>

<script>
import moment from 'moment'
import { STable, VSelect } from '@/components'
import productInfoDetailModal from './detailModal.vue'
import productInfoOfflineModal from './offlineModal.vue'
import { productBrandQuery } from '@/api/productBrand'
import { productTypeQuery } from '@/api/productType'
import { productList, productAudit, productBatchAudit, productDel, productOnline, productBatchOnline, productExport } from '@/api/product'
export default {
  components: { STable, VSelect, productInfoDetailModal, productInfoOfflineModal },
  data () {
    return {
      spinning: false,
      advanced: false, // 高级搜索 展开/关闭
      queryParam: { //  查询条件
        name: '', //  产品名称
        queryWord: '', // 产品编码/原厂编码
        productBrandSn: undefined, //  产品品牌
        productTypeSn1: '', //  产品一级分类
        productTypeSn2: '', //  产品二级分类
        productTypeSn3: '', //  产品三级分类
        state: undefined, //  产品状态
        pricingState: undefined //  定价状态
      },
      productType: [],
      disabled: false, //  查询、重置按钮是否可操作
      exportLoading: false,
      columns: [
        { title: '序号', dataIndex: 'no', width: 80, align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: 160, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'name', align: 'center', ellipsis: true, customRender: function (text) { return text || '--' } },
        { title: '产品编码', dataIndex: 'code', width: 220, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '原厂编码', dataIndex: 'origCode', width: 220, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '品牌', dataIndex: 'productBrandName', width: 200, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品分类', scopedSlots: { customRender: 'productType' }, width: 200, align: 'center' },
        { slots: { title: 'arrowFalgTitle' }, scopedSlots: { customRender: 'arrowFalg' }, width: 100, align: 'center' },
        { title: '最近修改时间', dataIndex: 'updateDate', width: 160, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品状态', dataIndex: 'stateDictValue', width: 140, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '定价状态', scopedSlots: { customRender: 'pricingState' }, width: 140, align: 'center' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: 250, align: 'center', fixed: 'right' }
      ],
      selectedRowKeys: [], // Check here to configure the default column
      selectedRows: [],
      loadingAudit: false,
      loadingLaunch: false,
      loadingDownline: false,
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        return productList(Object.assign(parameter, this.queryParam)).then(res => {
          const 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
          return data
        })
      },
      openModal: false, //  查看详情  弹框
      itemSn: '', //  当前sn
      openOfflineModal: false, //  下线  弹框
      offlineProductList: [], //  下线 当前所选数据
      productBrandList: [], //  品牌下拉数据
      productTypeList: [] //  分类下拉数据
    }
  },
  computed: {
    tableHeight () {
      return window.innerHeight - (this.advanced ? 425 : 370)
    },
    hasSelected () {
      return this.selectedRowKeys.length > 0
    },
    // 是否显示table选择框
    showSelect () {
      return this.$hasPermissions('B_productInfo_batchAudit') || this.$hasPermissions('B_productInfo_batchLaunch') || this.$hasPermissions('B_productInfo_batchDownline')
    }
  },
  methods: {
    onChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
    },
    onSelectChange (record, selected, selectedRows, nativeEvent) {
      const _this = this
      if (selected) { //  选择
        this.selectedRows.push(record)
      } else { //  取消
        this.selectedRows.map((item, index) => {
          if (item.id == record.id) {
            _this.selectedRows.splice(index, 1)
          }
        })
      }
    },
    // 本页全选/取消全选
    onSelectAllChange (selected, selectedRows, changeRows) {
      const _this = this
      if (selected) { //  选择
        this.selectedRows = [...this.selectedRows, ...changeRows]
      } else { //  取消
        this.selectedRows.map((item, index) => {
          this.selectedRows.map((subItem, ind) => {
            if (item.id == subItem.id) {
              _this.selectedRows.splice(index, 1)
            }
          })
        })
      }
    },
    // 审核
    handleAudit (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要审核吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          productAudit({ sn: row.productSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    // 批量审核
    handleBatchAudit () {
      const _this = this
      if (_this.selectedRowKeys.length < 1) {
        _this.$message.warning('请在列表勾选后再进行批量操作！')
        return
      }
      let num = 0
      const obj = []
      _this.selectedRows.map(item => {
        if (item.state == 'WAIT') {
          num++
          obj.push(item.productSn)
        }
      })
      if (num < 1) {
        _this.$message.warning('当前数据不可操作！')
        return
      }
      this.$confirm({
        title: '提示',
        content: '已选有效数据' + num + '条，确认要批量审核吗？',
        centered: true,
        onOk () {
          _this.loadingAudit = true
          _this.spinning = true
          productBatchAudit(obj).then(res => {
            _this.loadingAudit = false
            if (res.status == 200) {
              _this.selectedRowKeys = []
              _this.selectedRows = []
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    // 批量上线
    handleBatchLaunch () {
      const _this = this
      if (_this.selectedRowKeys.length < 1) {
        _this.$message.warning('请在列表勾选后再进行批量操作！')
        return
      }
      let num = 0
      const obj = []
      _this.selectedRows.map(item => {
        if (item.state == 'WAIT_ONLINE' || item.state == 'OFFLINE') {
          num++
          obj.push(item.productSn)
        }
      })
      if (num < 1) {
        _this.$message.warning('当前数据不可操作！')
        return
      }
      this.$confirm({
        title: '提示',
        content: '已选有效数据' + num + '条，确认要批量上线吗？',
        centered: true,
        onOk () {
          _this.loadingLaunch = true
          _this.spinning = true
          productBatchOnline(obj).then(res => {
            _this.loadingLaunch = false
            if (res.status == 200) {
              _this.selectedRowKeys = []
              _this.selectedRows = []
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    // 批量下线
    handleBatchDownline () {
      const _this = this
      if (_this.selectedRowKeys.length < 1) {
        _this.$message.warning('请在列表勾选后再进行批量操作！')
        return
      }
      let num = 0
      _this.offlineProductList = []
      _this.selectedRows.map(item => {
        if (item.state == 'ONLINE') {
          num++
          _this.offlineProductList.push({ productSn: item.productSn, code: item.code, commonProductList: [] })
        }
      })
      if (num < 1) {
        _this.$message.warning('当前数据不可操作！')
        return
      }
      this.openOfflineModal = true
    },
    //  重置
    resetSearchForm () {
      this.queryParam.name = ''
      this.queryParam.queryWord = ''
      this.queryParam.productBrandSn = undefined
      this.queryParam.productTypeSn1 = ''
      this.queryParam.productTypeSn2 = ''
      this.queryParam.productTypeSn3 = ''
      this.queryParam.state = undefined
      this.queryParam.pricingState = undefined
      this.productType = []
      this.$refs.table.refresh(true)
    },
    //  新增/编辑
    handleEdit (row) {
      if (row) { //  编辑
        this.$router.push({ path: `/productManagement/productInfo/edit/${row.id}/${row.productSn}` })
      } else { //  新增
        this.$router.push({ path: '/productManagement/productInfo/add' })
      }
    },
    // 上线
    handleLaunch (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要上线吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          productOnline({ sn: row.productSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    // 下线
    handleDownline (row) {
      this.offlineProductList.push({ productSn: row.productSn, code: row.code, commonProductList: [] })
      this.openOfflineModal = true
    },
    // 删除
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要删除吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          productDel({ sn: row.productSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    //  详情
    handleDetail (row) {
      this.itemSn = row.productSn
      this.openModal = true
    },
    //  关闭弹框
    closeModal () {
      this.itemSn = ''
      this.openModal = false
    },
    //  关闭下线弹框
    closeOfflineModal () {
      this.selectedRowKeys = []
      this.selectedRows = []
      this.offlineProductList = []
      this.openOfflineModal = false
    },
    //  导出
    handleExport () {
      const _this = this
      const params = this.queryParam
      this.exportLoading = true
      _this.spinning = true
      productExport(params).then(res => {
        this.exportLoading = false
        _this.spinning = false
        if (res.type == 'application/json') {
          var reader = new FileReader()
          reader.addEventListener('loadend', function () {
            const obj = JSON.parse(reader.result)
            _this.$notification.error({
              message: '提示',
              description: obj.message
            })
          })
          reader.readAsText(res)
        } else {
          this.download(res)
        }
      })
    },
    download (data) {
      if (!data) { return }
      const url = window.URL.createObjectURL(new Blob([data]))
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      const a = moment().format('YYYYMMDDHHmmss')
      const fname = '产品列表' + a
      link.setAttribute('download', fname + '.xlsx')
      document.body.appendChild(link)
      link.click()
    },
    //  产品分类  change
    changeProductType (val, opt) {
      this.queryParam.productTypeSn1 = val[0] ? val[0] : ''
      this.queryParam.productTypeSn2 = val[1] ? val[1] : ''
      this.queryParam.productTypeSn3 = val[2] ? val[2] : ''
    },
    //  产品品牌  列表
    getProductBrand () {
      productBrandQuery({}).then(res => {
        if (res.status == 200) {
          this.productBrandList = res.data
        } else {
          this.productBrandList = []
        }
      })
    },
    //  产品分类  列表
    getProductType () {
      productTypeQuery({}).then(res => {
        if (res.status == 200) {
          this.productTypeList = res.data
        } else {
          this.productTypeList = []
        }
      })
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.getProductBrand()
      vm.getProductType()
    })
  }
}
</script>
