<template>
  <div v-loading="loading" element-loading-text="拼命加载中......请稍等">
    <div>
      <el-form :inline="true">
        <el-form-item>
          <el-input
              v-model="search.entTaxId"
              clearable
              placeholder="请输入企业税号"
          >
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-input
              v-model="search.entName"
              clearable
              placeholder="请输入企业名称"
          >
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button
              @click="handleSearch"
              icon="el-icon-search"
              type="primary"
          >搜 索
          </el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <br/>
    <div>
      <el-container>
        <el-table
            :data="search.resultList"
            border
            style="width: 100%"
            :reserve-selection="true"
        >
          <el-table-column
              prop="entTaxId"
              label="企业税号"
              width="180"
              show-overflow-tooltip
          ></el-table-column>
          <el-table-column
              prop="entName"
              label="企业名称"
              width="180"
              show-overflow-tooltip
          ></el-table-column>
          <el-table-column
              prop="deviceType"
              label="设备类型"
              :formatter="fmtInitDevice"
              show-overflow-tooltip
          ></el-table-column>
          <el-table-column
              prop="taxDiscId"
              label="盘号"
              width="180"
              show-overflow-tooltip
          ></el-table-column>
          <el-table-column
              prop="taxMachineNo"
              label="税控服务器编号"
              width="120"
              show-overflow-tooltip
          ></el-table-column>
          <el-table-column
              prop="devicePos"
              label="设备端口位置"
              width="120"
              show-overflow-tooltip
          ></el-table-column>
          <el-table-column
              prop="isvPlatform"
              label="上架模式"
              :formatter="fmtISVPlatform"
              show-overflow-tooltip
          ></el-table-column>
          <el-table-column
              prop="statusChangeTime"
              label="状态改变时间"
              width="180"
              show-overflow-tooltip
          ></el-table-column>
          <el-table-column
              prop="initStatus"
              label="上架状态"
              :formatter="fmtInitStatus"
              align="center"
              fixed="right"
              width="120"
              show-overflow-tooltip
          ></el-table-column>
          <!-- <el-table-column
              prop="isConnected"
              label="可联通"
              :formatter="fmtIsConnected"
              align="center"
              fixed="right"
              show-overflow-tooltip
          ></el-table-column> -->
          <el-table-column
              prop="deviceId"
              label="设备id"
              width="180"
              show-overflow-tooltip
          ></el-table-column>
          <el-table-column
              label="操作"
              align="center"
              fixed="right"
              width="720"
          >
            <template slot-scope="scope">
              <el-button
                  @click="handleShowInvoiceStock(scope.row)"
                  type="primary"
              >
                发票领用存信息
              </el-button>
              <el-button
                  @click="handleEntDeviceSync(scope.row)"
                  type="primary"
              >
                企业设备终端同步
              </el-button>
              <el-button
                  @click="
                                    handleInvoiceRecoveryDialogShow(scope.row)
                                "
                  type="primary"
              >
                发票修复
              </el-button>
              <el-button
                  @click="
                                    handleOpenServicePackageDialog(scope.row)
                                "
                  type="primary"
              >
                开通服务
              </el-button>
              <el-button
                  @click="handleRemoveEntInitDevice(scope.row)"
                  type="primary"
              >
                设备下架
              </el-button>
              <el-button
                  @click="handleTaxDeclaration(scope.row)"
                  type="primary"
              >
                清 卡
              </el-button>
              <el-button
                  @click="changeInvoiceType(scope.row)"
                  type="primary">
                票种变更
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-container>
      <br/>
      <el-row type="flex" :gutter="20">
        <el-col :span="12"></el-col>
        <el-col :span="12">
          <div style="text-align: right">
            <el-pagination
                layout="total, sizes, prev, pager, next"
                :current-page="search.resultPagination.currentPage"
                :page-sizes="search.resultPagination.pageSizes"
                :page-size="search.resultPagination.pageSize"
                :total="search.resultPagination.total"
                @size-change="handleSearchResultSizeChange"
                @current-change="handleSearchResultCurrentChange"
            ></el-pagination>
          </div>
        </el-col>
      </el-row>
    </div>
    <el-dialog :visible.sync="invoiceStock.dialogVisible" center>
      <ent-invoice-stock
          :entTaxId="invoiceStock.entTaxId"
          :deviceType="invoiceStock.deviceType"
          :taxDiscId="invoiceStock.taxDiscId"
      ></ent-invoice-stock>
    </el-dialog>

    <el-dialog
        title="企业发票修复"
        :visible.sync="invoiceRecoveryDialog.visible"
        width="30%"
        append-to-body
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        @close="
                handleIinvoiceRecoveryDialogClose('invoiceRecoveryDialogForm')
            "
    >
      <div
          v-loading="invoiceRecoveryDialog.loading"
          element-loading-text="拼命加载中......请稍等"
      >
        <el-form
            :model="invoiceRecoveryDialog.form"
            :rules="invoiceRecoveryDialog.rules"
            ref="invoiceRecoveryDialogForm"
            label-position="top"
        >
          <el-form-item label="发票修复日期：" prop="dateRange">
            <el-date-picker
                v-model="invoiceRecoveryDialog.form.dateRange"
                type="daterange"
                unlink-panels
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 100%"
                :clearable="false"
            >
            </el-date-picker>
          </el-form-item>
          <br/>
          <el-form-item>
            <el-button
                type="primary"
                @click="
                                handleInvoiceRecoverySubmit(
                                    'invoiceRecoveryDialogForm'
                                )
                            "
            >立即修复
            </el-button
            >
            <el-button
                @click="invoiceRecoveryDialog.visible = false"
            >取 消
            </el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
    <el-dialog
        title="开通服务套餐"
        :visible.sync="selectedCommodityDialog.visible"
        width="70%"
        top="4vh"
        append-to-body
        @opened="handleSelectedCommodityDialogOpened"
        :close-on-click-modal="false"
    >
      <div
          v-loading="selectedCommodityDialog.loading"
          element-loading-text="拼命加载中"
      >
        <el-row :gutter="20">
          <el-col :span="14">
            <el-form :inline="true">
              <el-form-item>
                <el-select v-model="selectedCommodityDialog.search.type" placeholder="请选择商品类型">
                  <el-option v-for="item in selectedCommodityDialog.commodityOptions"
                             :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-input
                    v-model="selectedCommodityDialog.search.name"
                    placeholder="请输入商品名称"
                ></el-input>
              </el-form-item>

              <el-form-item v-if="isOpen === false">
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    @click="handleSearchCommodity"
                >搜索
                </el-button
                >
              </el-form-item>
              <el-form-item v-if="isOpen === true">
                <el-button type="primary" @click="handleSubmitSelectCommodity(null)">保 存</el-button>
              </el-form-item>
            </el-form>
            <div style="margin-bottom: 10px; margin-left: 5px">
              <el-switch
                  v-model="isOpen"
                  inactive-text="是否仅开通企业代账机构对应的服务">
              </el-switch>
            </div>
            <el-table
                v-if="isOpen === false"
                :data="selectedCommodityDialog.search.resultList"
                border
                stripe
                style="width: 100%"
                height="300px"
            >
              <el-table-column
                  type="index"
                  :index="pageIndex"
                  align="center"
                  label="序号"
                  width="50"
              ></el-table-column>
              <el-table-column
                  prop="productName"
                  label="商品名称"
                  show-overflow-tooltip
              ></el-table-column>
              <el-table-column
                  prop="type"
                  label="商品类型"
                  width="110"
                  align="center"
                  :formatter="fmtCommodityType"
                  show-overflow-tooltip
              ></el-table-column>
              <el-table-column
                  prop="oriPrice"
                  label="产品原价（元）"
                  width="110"
                  align="center"
                  show-overflow-tooltip
              ></el-table-column>
              <el-table-column
                  prop="favouredPrice"
                  label="折扣后价格（元）"
                  width="120"
                  align="center"
                  show-overflow-tooltip
              ></el-table-column>
              <el-table-column
                  prop="createTime"
                  label="创建时间"
                  width="140"
                  align="center"
                  show-overflow-tooltip
              ></el-table-column>
              <el-table-column
                  label="是否启用"
                  width="70"
                  align="center"
              >
                <template slot-scope="scope">
                  <el-switch
                      disabled
                      v-model="scope.row.enable"
                  >
                  </el-switch>
                </template>
              </el-table-column>
              <el-table-column
                  label="操作"
                  width="120"
                  align="center"
                  fixed="right"
              >
                <template slot-scope="scope">
                  <el-button type="primary" @click="handleSubmitSelectCommodity(scope.row)">选择此商品</el-button>
                </template>
              </el-table-column>
            </el-table>
            <br/>
            <div style="text-align: right" v-if="isOpen === false">
              <el-pagination
                  layout="total, sizes, prev, pager, next"
                  :current-page="
                                    selectedCommodityDialog.search
                                        .resultPagination.currentPage
                                "
                  :page-sizes="
                                    selectedCommodityDialog.search
                                        .resultPagination.pageSizes
                                "
                  :page-size="
                                    selectedCommodityDialog.search
                                        .resultPagination.pageSize
                                "
                  :total="
                                    selectedCommodityDialog.search
                                        .resultPagination.total
                                "
                  @size-change="
                                    handleSearchCommodityResultSizeChange
                                "
                  @current-change="
                                    handleSearchCommodityResultCurrentChange
                                "
              ></el-pagination>
            </div>
          </el-col>
          <el-col :span="10">
            <el-card>
              <p>
                企业名称：{{
                  selectedCommodityDialog.entInfo.entName
                }}
              </p>
              <p>
                企业税号：{{
                  selectedCommodityDialog.entInfo.entTaxId
                }}
              </p>
              <p>
                企业类型：{{
                  fmtInitDevice(
                      "",
                      "",
                      selectedCommodityDialog.entInfo
                          .deviceType
                  )
                }}
              </p>
              <p>
                税控设备编号：{{
                  selectedCommodityDialog.entInfo.taxDiscId
                }}
              </p>
              <el-divider></el-divider>
              <div
                  v-if="
                                    !!selectedCommodityDialog.entBaseServicePackage
                                "
              >
                <p>
                  基础服务包：{{
                    selectedCommodityDialog
                        .entBaseServicePackage.productName
                  }}
                </p>
                <p>
                  开通时间：{{
                    selectedCommodityDialog
                        .entBaseServicePackage.effectiveTime
                  }}
                </p>
              </div>
              <div v-else>
                <p>未购买基础服务</p>
              </div>

              <h4>开通服务列表：</h4>
              <el-table
                  :data="selectedCommodityDialog.entServices"
                  border
                  stripe
                  style="width: 100%"
                  height="300px"
              >
                <el-table-column
                    type="index"
                    align="center"
                    label="序号"
                    width="50"
                ></el-table-column>
                <el-table-column
                    prop="featureName"
                    label="服务名称"
                    width="80"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                    prop="featureLevel"
                    label="服务级别"
                    width="70"
                    align="center"
                ></el-table-column>
                <el-table-column
                    label="服务信息"
                    align="center"
                >
                  <template slot-scope="scope">
                                        <span v-if="scope.row.limitType == 1"
                                        >服务时间：{{
                                            scope.row.beginDate
                                          }}
                                            - {{ scope.row.endDate }}</span
                                        >
                    <span v-if="scope.row.limitType == 2"
                    >剩余次数：{{
                        scope.row.surplus
                      }}</span
                    >
                  </template>
                </el-table-column>
                <el-table-column
                    label="操作"
                    width="80"
                    align="center"
                    fixed="right"
                >
                  <template slot-scope="scope">
                    <el-button type="primary" @click="selectDelay(scope.row)">延期</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
    <el-dialog
        title="发票修复详情"
        :visible.sync="isRepairShow"
        width="30%"
        append-to-body
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        @close="repairClose"
    >
      <div style="display: flex; justify-content: center; align-items: center; flex-direction: column">
        <el-progress type="circle" :percentage="progress" :status="progressStatus"></el-progress>
        <div style="display: flex; flex-direction: row">
          <div style="display: flex; justify-content: center; align-items: center">
            <p>发票修复情况：</p>
          </div>
          <div>
            <p>发票修复成功{{ successNumber }}条</p>
            <p>发票修复失败{{ failNumber }}条</p>
          </div>
        </div>
      </div>
    </el-dialog>
    <el-dialog
        title="延期天数"
        :visible.sync="isDelay"
        width="30%"
        :close-on-click-modal="false"
        :before-close="delayClose">
      <div style="display: flex; justify-content: center; align-items: center">
        <span>延期天数：</span>
        <el-input type="number" style="width: 200px" v-model="days" placeholder="请输入需要延期的天数"></el-input>
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button @click="delayClose">取 消</el-button>
    <el-button type="primary" @click="delayData">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  EntDeviceQuery,
  EntDeviceSync,
  EntFindDevice,
  findEntInitDevice,
  removeEntInitDevice
} from '@/api/ent_init'
import EntInvoiceStock from './components/ent_invoice_stock'
import SKServer from '@/api/skserver'
import CommodityService from '@/api/commodity'
import cache from "@/utils/cache";
import {AxiosRequestByBearer} from "@/data/axios_request";
import axios from "axios";
import {AxiosRequestData} from "../../data/axios_request";

// 商品类型
const commodityOptions = [
  {
    value: 'base',
    label: '基础主体套餐'
  },
  {
    value: 'ext',
    label: '附加增值套餐'
  }
]

// 上架设备类型列表
const initDeviceTypes = [
  {
    value: 1,
    label: '软证书'
  },
  {
    value: 2,
    label: '税控盘'
  },
  {
    value: 3,
    label: '金税盘'
  },
  {
    value: 4,
    label: '税控UKey'
  },
  {
    value: 5,
    label: '税控服务器'
  }
]

// 上架模式列表
const isvPlatformOptions = [
  {
    value: 1,
    label: '上架模式1'
  },
  {
    value: 2,
    label: '上架模式2'
  }
]

// 企业服务状态选项列表
const initStatusOptions = [
  {
    value: 1,
    label: '待初始化'
  },
  {
    value: 2,
    label: '初始化成功'
  },
  {
    value: 3,
    label: '初始化中'
  },
  {
    value: 4,
    label: '初始化失败'
  },
  {
    value: 5,
    label: '上架成功'
  },
  {
    value: 6,
    label: '已下架'
  },
  {
    value: 99,
    label: '未知状态'
  }
]

export default {
  name: 'EntInitDevice',
  components: {
    'ent-invoice-stock': EntInvoiceStock
  },
  data() {
    return {
      loading: false,
      search: {
        entTaxId: null,
        entName: '',
        resultList: [],
        resultPagination: {
          currentPage: 1,
          pageSizes: [10, 30, 50, 100],
          pageSize: 10,
          total: 0
        }
      },
      invoiceStock: {
        dialogVisible: false,
        entTaxId: '',
        deviceType: '',
        taxDiscId: ''
      },
      invoiceRecoveryDialog: {
        visible: false,
        loading: false,
        rowData: null,
        form: {
          dateRange: ''
        },
        rules: {
          dateRange: [
            {
              required: true,
              message: '请选择企业发票修复日期范围',
              trigger: 'change'
            }
          ]
        }
      },
      selectedCommodityDialog: {
        visible: false,
        loading: false,
        entInfo: {}, // 上架企业信息
        commodityOptions: commodityOptions,
        search: {
          type: 'base', // 商品类型
          name: '', // 商品名称
          resultList: [],
          resultPagination: {
            currentPage: 1,
            pageSizes: [10, 30, 50, 100],
            pageSize: 10,
            total: 0
          }
        },
        entServices: [], // 企业开通服务列表
        entBaseServicePackage: {} // 企业设备购买的基础服务
      },
      isRepairShow: false,
      successNumber: 0,
      failNumber: 0,
      progress: 0,
      progressStatus: null,
      socketUrl: 'wss://www.chtax.cn/api/sys/websocket/',
      socket: {},
      socketId: '',
      socketTimer: null,
      isOpen: false,
      isDelay: false,
      days: 1,
      account: '',
      taxDiscId: '',
      deviceType: '',
      featureId: '',
      entTaxId: '',
      token: ''
    }
  },
  created() {
    this.search.entTaxId = this.$route.params.key
    let user = JSON.parse(cache.getLocal('user'))
    this.account = user.account
    this.token = cache.getToken()
    this.callFindEntInitDevice(
        this.search.resultPagination.currentPage,
        this.search.resultPagination.pageSize
    )
  },
  methods: {
    fmtInitDevice(row, column, cellValue) {
      let result = cellValue
      for (const item of initDeviceTypes) {
        if (item.value === cellValue) {
          result = item.label
          break
        }
      }
      return result
    },
    fmtISVPlatform(row, column, cellValue) {
      let result = cellValue
      for (const item of isvPlatformOptions) {
        if (item.value === cellValue) {
          result = item.label
          break
        }
      }
      return result
    },
    fmtInitStatus(row, column, cellValue) {
      let result = cellValue
      for (const item of initStatusOptions) {
        if (item.value === cellValue) {
          result = item.label
          break
        }
      }
      return result
    },
    fmtIsConnected(row, column, cellValue) {
      return cellValue ? '可连通' : '不可连通'
    },
    handleSearch() {
      this.callFindEntInitDevice(
          1,
          this.search.resultPagination.pageSize
      )
    },
    handleSearchResultSizeChange(val) {
      this.callFindEntInitDevice(1, val)
    },
    handleSearchResultCurrentChange(val) {
      this.callFindEntInitDevice(
          val,
          this.search.resultPagination.pageSize
      )
    },
    handleShowInvoiceStock(row) {
      this.invoiceStock.dialogVisible = true

      this.invoiceStock.entTaxId = row.entTaxId
      this.invoiceStock.deviceType = row.deviceType
      this.invoiceStock.taxDiscId = row.taxDiscId
    },
    handleEntDeviceSync(row) {
      let _this = this
      _this.loading = true
      let entTaxId = row.entTaxId
      let deviceType = row.deviceType
      let taxDiscId = row.taxDiscId
      EntDeviceSync(entTaxId, deviceType, taxDiscId)
          .then((val) => {
            _this.loading = false
            _this.$message.success(val.msg)
          })
          .catch((err) => {
            _this.loading = false
            _this.$message.error(err)
          })
    },
    /**
     * 企业设备信息查询
     * @param {Number} pageNum : 当前页码
     * @param {Number} pageSize : 每页数量
     */
    callFindEntInitDevice(pageNum, pageSize) {
      let _this = this
      _this.loading = true
      findEntInitDevice({
        entTaxId: _this.search.entTaxId,
        entName: _this.search.entName,
        pageNum: pageNum,
        pageSize: pageSize
      })
          .then((val) => {
            _this.search.resultPagination.total = val.data.total
            _this.search.resultPagination.pageSize = val.data.size
            _this.search.resultPagination.currentPage =
                val.data.current
            _this.search.resultList = val.data.records
            // _this.$message.success(val.msg);
          })
          .catch((err) => {
            _this.$message.error(err)
          })
          .finally(() => {
            _this.loading = false
          })
    },
    // 发票修复
    handleInvoiceRecoveryDialogShow(row) {
      this.invoiceRecoveryDialog.rowData = row
      this.invoiceRecoveryDialog.visible = true
    },
    // 发票修复 操作提交
    handleInvoiceRecoverySubmit(formName) {
      let _this = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let beginTime = ''
          let endTime = ''
          let tempForm = this.invoiceRecoveryDialog.form
          if (tempForm.dateRange instanceof Array) {
            beginTime = tempForm.dateRange[0]
            endTime = tempForm.dateRange[1]
            beginTime = this.dateFormat(
                new Date(beginTime),
                'yyyy-MM-dd'
            )
            let endTimeObj = new Date(endTime)
            endTime = this.dateFormat(
                new Date(
                    endTimeObj.getFullYear(),
                    endTimeObj.getMonth(),
                    endTimeObj.getDate(),
                    '23',
                    '59',
                    '59'
                ),
                'yyyy-MM-dd'
            )
          } else {
            this.$message.error(
                '起始日期与结束日期为必输项，请确定后重试！'
            )
            return false
          }

          // 发票修复
          _this.invoiceRecoveryDialog.loading = true
          SKServer.deviceInvoiceRecovery({
            tax_no: _this.invoiceRecoveryDialog.rowData.entTaxId,
            device_no:
            _this.invoiceRecoveryDialog.rowData.taxDiscId,
            start_date: beginTime,
            end_date: endTime
          })
              .then((val2) => {
                _this.$message.success(
                    '发票修复请求提交成功！' + val2.message
                )
                _this.socketId = val2.data
                this.initSocket()
                _this.invoiceRecoveryDialog.visible = false
                _this.isRepairShow = true
              })
              .catch((err2) => {
                _this.$message.error(
                    '发票修复请求提交失败！' + err2
                )
              })
              .finally(() => {
                _this.invoiceRecoveryDialog.loading = false
              })
        } else {
          return false
        }
      })
    },
    handleIinvoiceRecoveryDialogClose(formName) {
      this.invoiceRecoveryDialog.originalRow = null
      this.$refs[formName].resetFields()
    },
    dateFormat(date, fmt) {
      // 小时只支持24小时制
      var o = {
        'M+': date.getMonth() + 1, // 月份
        'd+': date.getDate(), // 日
        'H+': date.getHours(), // 24小时,
        'm+': date.getMinutes(), // 分
        's+': date.getSeconds(), // 秒
        'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
        S: date.getMilliseconds() // 毫秒
      }
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(
            RegExp.$1,
            (date.getFullYear() + '').substr(4 - RegExp.$1.length)
        )
      }
      for (var k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
          fmt = fmt.replace(
              RegExp.$1,
              RegExp.$1.length == 1
                  ? o[k]
                  : ('00' + o[k]).substr(('' + o[k]).length)
          )
        }
      }
      return fmt
    },
    handleOpenServicePackageDialog(row) {
      this.deviceType = row.deviceType
      this.taxDiscId = row.taxDiscId
      this.entTaxId = row.entTaxId
      this.selectedCommodityDialog.entInfo = row

      // 显示弹窗
      this.selectedCommodityDialog.visible = true
    },
    handleSelectedCommodityDialogOpened() {
      this.refreshEntServiceInfo()
    },
    // 刷新企业服务信息
    refreshEntServiceInfo() {
      this.selectedCommodityDialog.entServices = []
      this.selectedCommodityDialog.entBaseServicePackage = {}

      this.selectedCommodityDialog.loading = true
      let _this = this
      CommodityService.findEntBaseServicePackge({
        entTaxId: _this.selectedCommodityDialog.entInfo.entTaxId,
        deviceType: _this.selectedCommodityDialog.entInfo.deviceType,
        taxDiscId: _this.selectedCommodityDialog.entInfo.taxDiscId
      })
          .then((val) => {
            _this.selectedCommodityDialog.entBaseServicePackage = val.data
            return CommodityService.findEntServices({
              entTaxId:
              _this.selectedCommodityDialog.entInfo.entTaxId,
              deviceType:
              _this.selectedCommodityDialog.entInfo.deviceType,
              taxDiscId:
              _this.selectedCommodityDialog.entInfo.taxDiscId,
              pageNum: 1,
              pageSize: 1000
            })
          })
          .then((val) => {
            _this.selectedCommodityDialog.entServices = val.data.records
            val.data.records.forEach((item, index) => {
              if (item.featureName === '托管服务') {
                if (item.endDate === '9999-01-01 00:00:00') {
                  this.isOpen = true
                }
              }
            })
            if (!this.isOpen) {
              this.handleSearchCommodity()
            }
          })
          .catch((err) => {
            _this.$message.error(err)
          })
          .finally(() => {
            _this.selectedCommodityDialog.loading = false
          })
    },
    pageIndex(index) {
      let currentPage = this.selectedCommodityDialog.search
          .resultPagination.currentPage // 当前页码，具体看组件取值
      let pageSize = this.selectedCommodityDialog.search.resultPagination
          .pageSize // 每页条数，具体是组件取值
      return index + 1 + (currentPage - 1) * pageSize
    },
    fmtCommodityType(row, column, cellValue) {
      let result = cellValue
      for (const item of commodityOptions) {
        if (item.value === cellValue) {
          result = item.label
          break
        }
      }
      return result
    },
    // 查询产品
    handleSearchCommodity() {
      this.callFind(
          1,
          this.selectedCommodityDialog.search.resultPagination.pageSize
      )
    },
    handleSearchCommodityResultSizeChange(val) {
      this.callFind(1, val)
    },
    handleSearchCommodityResultCurrentChange(val) {
      this.callFind(
          val,
          this.selectedCommodityDialog.search.resultPagination.pageSize
      )
    },
    callFind(pageNum, pageSize) {
      this.selectedCommodityDialog.loading = true
      let _this = this
      CommodityService.find({
        productName: this.selectedCommodityDialog.search.name,
        type: this.selectedCommodityDialog.search.type,
        pageNum: pageNum,
        pageSize: pageSize
      })
          .then((val) => {
            _this.selectedCommodityDialog.search.resultPagination.total =
                val.data.total
            _this.selectedCommodityDialog.search.resultPagination.pageSize =
                val.data.size
            _this.selectedCommodityDialog.search.resultPagination.currentPage =
                val.data.current
            _this.selectedCommodityDialog.search.resultList =
                val.data.records
          })
          .catch((err) => {
            _this.$message.error(err)
          })
          .finally(() => {
            _this.selectedCommodityDialog.loading = false
          })
    },
    // 提交选择的商品
    handleSubmitSelectCommodity(row) {
      let productId = null
      if (row) {
        productId = row.productId
      }
      let _this = this
      this.$confirm('此操作将为该企业设定商品，请确认?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
          .then(() => {
            // 确定
            _this.selectedCommodityDialog.loading = true
            let args = {
              entTaxId: _this.selectedCommodityDialog.entInfo.entTaxId,
              deviceType: _this.selectedCommodityDialog.entInfo.deviceType,
              taxDiscId: _this.selectedCommodityDialog.entInfo.taxDiscId,
              productId: productId,
              bagentFeatures: this.isOpen
            }
            CommodityService.saveEntProduct(args)
                .then((val) => {
                  _this.$message.success(val.msg)
                  // 刷新企业服务信息
                  _this.refreshEntServiceInfo()
                })
                .catch((err) => {
                  _this.$message.error(err)
                })
                .finally(() => {
                  _this.selectedCommodityDialog.loading = false
                })
          })
          .catch(() => {
            // 无取消操作
          })
    },
    // 设备下架
    handleRemoveEntInitDevice(row) {
      let _this = this
      // this.$confirm("此操作将下架企业开票设备，请确认?", "提示", {
      //     confirmButtonText: "确定",
      //     cancelButtonText: "取消",
      //     type: "warning",
      // })
      this.$prompt('此操作将下架企业开票设备，请输入下架说明：', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        center: true
      })
          .then(({value}) => {
            // 确定
            _this.loading = true
            let args = {
              entTaxId: row.entTaxId,
              deviceType: row.deviceType,
              taxDiscId: row.taxDiscId,
              remark: value
            }
            removeEntInitDevice(args)
                .then((val) => {
                  _this.$message.success(val.msg)
                  // 刷新企业设备列表
                  _this.callFindEntInitDevice(
                      _this.search.resultPagination.currentPage,
                      _this.search.resultPagination.pageSize
                  )
                })
                .catch((err) => {
                  _this.$message.error(err)
                })
                .finally(() => {
                  _this.loading = false
                })
          })
          .catch(() => {
            // 无取消操作
          })
    },
    handleTaxDeclaration(row) {
      this.loading = true
      let _this = this
      SKServer.taxDeclaration(row.entTaxId, row.taxDiscId)
          .then((val) => {
            _this.$message.success('成功！')
          })
          .catch((err) => {
            _this.$message.error(err)
          })
          .finally(() => {
            _this.loading = false
          })
    },
    // 变更票种
    async changeInvoiceType(row) {
      this.loading = true
      const url = '/v1/sk/change_invoice_category_manage'
      let token = cache.getToken()
      let args = {
        tax_no: row.entTaxId,
        device_no: row.taxDiscId
      }
      let req = await AxiosRequestByBearer(
          url,
          token,
          args,
          false,
          1
      )
      if (req) {
        if (req.code === 200) {
          this.loading = false
          this.$message({
            message: req.message,
            type: 'success'
          })
        } else {
          this.loading = false
          this.$message.error(req.message)
        }
      } else {
        this.loading = false
      }
    },
    initSocket() {
      // 实例化socket，这里的实例化直接赋值给this.ws是为了后面可以在其它的函数中也能调用websocket方法，例如：this.ws.close(); 完成通信后关闭WebSocket连接
      this.socket = new WebSocket(this.socketUrl + this.socketId)
      // 监听是否连接成功
      this.socket.onopen = () => {
        console.log('ws连接状态：' + this.socket.readyState)
        // 连接成功则发送一个数据
        this.socket.send('连接成功')
      }
      // // 接听服务器发回的信息并处理展示
      // this.socket.onmessage = (data) => {
      //   console.log('接收到来自服务器的消息：')
      //   console.log(data)
      // }
      // let send = this.socket.send('ping')
      // console.log('send')
      // console.log(send)
      // 监听连接关闭事件
      // this.socket.onclose = () => {
      //   // 监听整个过程中websocket的状态
      //   console.log('ws连接状态：' + this.socket.readyState)
      // }
      //
      // // 监听并处理error事件
      // this.socket.onerror = function(error) {
      //   console.log(error)
      // }
      this.getInvoiceWebSocket()
    },
    // 循环查询修复进度数据
    getInvoiceWebSocket() {
      this.socketTimer = setInterval(() => {
        // 接听服务器发回的信息并处理展示
        this.socket.onmessage = (data) => {
          let invoiceData = JSON.parse(data.data)
          this.successNumber = invoiceData.success
          this.failNumber = invoiceData.failure
          let total = invoiceData.success + invoiceData.failure
          let progressNum = parseInt((total / invoiceData.total * 100).toString())
          this.progress = progressNum
          if (invoiceData.total === total) {
            this.progressStatus = 'success'
          }
          if (invoiceData.status === 2) {
            if (invoiceData.total !== total) {
              this.progressStatus = 'warning'
            }
            this.$message({
              message: invoiceData.message,
              type: 'warning'
            })
            clearInterval(this.socketTimer)
          }
        }
        // 监听连接关闭事件
        this.socket.onclose = () => {
          // 监听整个过程中websocket的状态
          console.log('定时器链接状态')
          console.log('ws连接状态：' + this.socket.readyState)
          clearInterval(this.socketTimer)
        }
      }, 10000)
    },
    // 发票修复状态页面关闭
    repairClose() {
      this.successNumber = 0
      this.failNumber = 0
      this.progress = 0
      this.progressStatus = null
      this.socket = {}
      this.socketTimer = null
    },
    // 选择延期天数
    selectDelay(row) {
      this.featureId = row.featureId
      this.isDelay = true
    },
    // 延期页面关闭调用
    delayClose() {
      this.days = 1
      this.isDelay = false
    },
    // 服务延期
    async delayData() {
      if (this.token) {
        const url = '/marketing/ent/features/delayDays'
        let response = await AxiosRequestData(
            url,
            this.token,
            {
              entTaxId: this.entTaxId,
              taxDiscId: this.taxDiscId,
              deviceType: this.deviceType,
              featureId: this.featureId,
              delayDays: this.days,
              mobile: this.account,
              reqChannel: 4
            },
            false,
            1
        )
        if (response) {
          if (response.code === 0) {
            this.isDelay = false
            this.selectedCommodityDialog.visible = false
            this.$message({
              message: '延期成功！',
              type: 'success'
            })
          } else {
            this.$message.error(response.msg)
          }
        }
      }
    }
  }
}
</script>

<style scoped>
</style>
