<template>
  <div class="app-container root">
    <div class="filter-container">
      <sticky style="margin-bottom: 10px">
        <div class="sub-navbar">
          <el-button
            icon="el-icon-edit"
            type="primary"
            size="medium"
            @click="convertBjd"
          >
            生成报检项目
          </el-button>
          <el-button type="primary" size="medium" @click="insertCart">
            <svg-icon icon-class="shoppingCard" />&nbsp;批量加入购物车
          </el-button>
          <el-dropdown style="margin-left: 10px" @command="handleCommand">
            <el-button type="success" size="medium">
              新建报检单<i class="el-icon-arrow-down el-icon--right" />
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                v-for="item in sbzlList"
                :key="item.value"
                :command="item"
              >
                {{ item.label }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <div style="float: right">
            <el-badge :value="shoppingSize" :max="99" class="item">
              <el-popover placement="bottom" width="600" trigger="hover">
                <div class="filter-container" style="padding-bottom: 3px">
                  <el-button
                    icon="el-icon-sold-out"
                    type="primary"
                    @click="convertBjdByCart"
                  >
                    生成项目
                  </el-button>
                  <el-button
                    type="danger"
                    icon="el-icon-circle-close-outline"
                    @click="clearCart"
                  >
                    清空购物车
                  </el-button>
                </div>
                <el-table
                  ref="shoppingTable"
                  v-adaptive="{ bottomOffset: 50 }"
                  height="0"
                  :data="shoppingCartData"
                  border
                  style="width: 100%"
                  @selection-change="handleCartSelectionChange"
                  @row-click="checkCartSelection"
                >
                  <el-table-column type="selection" width="40" />
                  <el-table-column align="center" label="操作" min-width="65">
                    <template slot-scope="scope">
                      <el-button
                        type="danger"
                        icon="el-icon-delete"
                        @click="removeCart(scope.$index)"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column label="设备种类" prop="shebeizhonglei" />
                  <el-table-column
                    prop="zhucedaima"
                    label="注册代码"
                    min-width="120"
                  />
                  <el-table-column
                    prop="chanpinbianhao"
                    label="出厂编号"
                    min-width="90"
                  />
                  <el-table-column
                    prop="shiyongdengjibianhao"
                    label="使用登记证号"
                    min-width="90"
                  />
                </el-table>
                <el-button slot="reference" type="primary">
                  <svg-icon icon-class="shoppingCard" />
                </el-button>
              </el-popover>
            </el-badge>
          </div>
        </div>
      </sticky>
      <el-form>
        <el-form-item>
          <el-select
            v-model="listQuery.shebeizhongleidaima"
            placeholder="请选择设备种类"
            clearable
            style="width: 160px"
          >
            <el-option
              v-for="item in sbzlList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-input
            v-model="listQuery.shiyongdanwei"
            placeholder="使用单位名称"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleFilter"
          />
          <el-input
            v-model="listQuery.shigongdanwei"
            placeholder="施工单位名称"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleFilter"
          />
          <el-input
            v-model="listQuery.zhucedaima"
            placeholder="请从第一位开始输入注册代码"
            clearable
            style="width: 220px"
            @keyup.enter.native="handleFilter"
          />
          <el-input
            v-model="listQuery.shiyongdengjibianhao"
            placeholder="使用登记证编号"
            clearable
            style="width: 160px"
            @keyup.enter.native="handleFilter"
          />
          <el-input
            v-model="listQuery.danweineibubianhao"
            placeholder="单位内部编号"
            clearable
            style="width: 160px"
            @keyup.enter.native="handleFilter"
          />
          <el-button type="primary" icon="el-icon-search" @click="handleFilter">
            查询
          </el-button>
          <el-button type="info" icon="el-icon-clear" @click="clearSearch">
            清除
          </el-button>
          <br>
          <el-input
            v-model="listQuery.zhizaodanwei"
            placeholder="制造单位名称"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleFilter"
          />
          <el-input
            v-model="listQuery.chanpinbianhao"
            placeholder="出厂编号"
            clearable
            style="width: 160px"
            @keyup.enter.native="handleFilter"
          />
          <el-select
            v-model="listQuery.quhuadaima"
            placeholder="请选择所属区划"
            clearable
            value=""
            style="width: 140px"
            @change="handleFilter"
          >
            <el-option
              v-for="item in areas"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-date-picker
            v-model="listQuery.xiacijianyanriqiStart"
            type="date"
            placeholder="下次检验日期（起）"
            style="width: 150px"
          />
          <el-date-picker
            v-model="listQuery.xiacijianyanriqiEnd"
            type="date"
            placeholder="下次检验日期（止）"
            style="width: 150px"
          />
          <el-input
            v-model="listQuery.zhucedaimaqi"
            placeholder="注册代码起始（全）"
            clearable
            style="width: 220px"
          />
          <el-input
            v-model="listQuery.zhucedaimazhi"
            placeholder="注册代码截止（全）"
            clearable
            style="width: 220px"
          />
        </el-form-item>
      </el-form>
    </div>
    <el-table
      ref="baseTable"
      v-adaptive="{ bottomOffset: 50 }"
      height="0"
      :data="list"
      :row-class-name="tableRowClassName"
      border
      fit
      highlight-current-row
      @selection-change="handleSelectionChange"
      @row-click="checkSelection"
    >
      <el-table-column type="selection" width="45" />
      <el-table-column align="center" label="序号" width="60">
        <template slot-scope="scope">
          <span v-text="getIndex(scope.$index)" />
        </template>
      </el-table-column>
      <el-table-column
        :formatter="clearBlank"
        align="center"
        label="报告编号"
        prop="baogaobianhao"
        min-width="100"
      />
      <el-table-column
        align="center"
        label="设备种类"
        prop="shebeizhonglei"
        min-width="60"
      />
      <el-table-column
        align="center"
        label="使用单位"
        prop="shiyongdanwei"
        min-width="150"
      />
      <el-table-column
        v-if="departmentId !== 75"
        :formatter="clearBlank"
        align="center"
        label="注册代码"
        prop="zhucedaima"
        min-width="130"
      />
      <el-table-column
        :formatter="clearBlank"
        align="center"
        label="使用登记证编号"
        prop="shiyongdengjibianhao"
        min-width="90"
      />
      <el-table-column
        v-if="departmentId === 70"
        :formatter="clearBlank"
        align="center"
        label="设备名称"
        prop="shebeimingcheng"
        min-width="90"
      />
      <el-table-column
        :formatter="clearBlank"
        align="center"
        label="规格型号"
        prop="guigexinghao"
        min-width="110"
      />
      <el-table-column
        :formatter="clearBlank"
        align="center"
        label="出厂编号"
        prop="chanpinbianhao"
        min-width="80"
      />
      <el-table-column
        :formatter="clearBlank"
        align="center"
        label="单位内部编号"
        prop="danweineibubianhao"
        min-width="60"
      />
      <el-table-column
        :formatter="clearBlank"
        align="center"
        label="下次检验日期"
        prop="xiacijianyanriqi"
        min-width="70"
      />
      <el-table-column
        :formatter="clearBlank"
        align="center"
        label="区划名称"
        prop="quhuamingcheng"
        min-width="50"
      />
      <el-table-column
        :formatter="formmatState"
        align="center"
        label="流转状态"
        prop="state"
        min-width="50"
      />
      <el-table-column align="center" label="操作" min-width="50">
        <template slot-scope="scope">
          <el-button type="primary" @click="addToCart(scope.$index)">
            <svg-icon icon-class="shoppingCard" />
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="uFlex mt-10">
      <pagination
        v-show="totalCount > 0"
        :total="totalCount"
        :page-num.sync="listQuery.pageNum"
        :page-row.sync="listQuery.pageRow"
        @pagination="getList"
      />
      <div class="uFlex">
        <div class="tips1">
          超期预警
        </div>
        <div class="tips2">
          到期标注
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import Sticky from '@/components/Sticky'
import Pagination from '@/components/Pagination'
export default {
  name: 'CreateProjectDJ',
  components: { Sticky, Pagination },
  data() {
    return {
      totalCount: 0,
      shoppingSize: 0,
      list: [],
      listQuery: {
        pageNum: 1, // 页码
        pageRow: 20, // 每页条数
        order: 'asc', // 排序字段
        sort: 'zhucedaima', // 排序方式
        shidaima: '3701',
        shebeizhongleidaima: ''
      },
      sbzlList: [],
      areas: [],
      shoppingCartData: [],
      multipleSelection: [], // 多选数组
      multipleCartSelection: [],
      departmentId: this.$store.getters.departmentId
    }
  },
  created() {
    // this.getList()
    this.getSbzlList()
    this.getArea()
  },
  mounted() {
    switch (this.departmentId) {
      case 68:
        this.listQuery.shebeizhongleidaima = '8000'
        break
      case 70:
        this.listQuery.shebeizhongleidaima = '2000'
        break
      case 75:
        this.listQuery.shebeizhongleidaima = '1000'
        break
      case 83:
        this.listQuery.shebeizhongleidaima = '2000'
        break
      case 73:
        this.listQuery.shebeizhongleidaima = '3000'
        break
      default:
        this.listQuery.shebeizhongleidaima = ''
        break
    }
  },
  methods: {
    getList() {
      // 查询列表
      this.apibjd({
        url: '/se/list',
        method: 'get',
        params: this.listQuery
      }).then((data) => {
        if (data.list.length === 0) {
          this.$confirm(
            '省局监察未登记该设备信息，点“确定”执行本地查询或“取消”更换查询条件！！',
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
          )
            .then(() => {
              this.apibjd({
                url: '/baseinfo/listDating',
                method: 'get',
                params: this.listQuery
              }).then((data) => {
                this.list = data.list
                this.totalCount = data.total
              })
            })
            .catch(() => {
              return false
            })
        } else {
          this.list = data.list
          this.totalCount = data.total
        }
      })
    },
    getSbzlList() {
      this.api({
        url: '/sedirectory/getList',
        method: 'get',
        params: {
          sbzl: undefined,
          level: '1'
        }
      }).then((data) => {
        this.sbzlList = data
      })
    },
    getArea() {
      // 查询区划
      this.api({
        url: '/area/getShiArea',
        method: 'get',
        params: {
          shidaima: '370100'
        }
      }).then((data) => {
        this.areas = data
      })
    },
    handleCommand(item) {
      this.$router.push({
        path:
          '/bjd/bjd-dj-input/null/' +
          item.value +
          '/' +
          item.label +
          '/newBuild'
      })
    },
    getIndex($index) {
      // 表格序号
      return (this.listQuery.pageNum - 1) * this.listQuery.pageRow + $index + 1
    },
    handleFilter() {
      // 查询事件
      if (!this.listQuery.shebeizhongleidaima) {
        this.$message({
          message: '请先选择设备种类',
          type: 'warning'
        })
      } else {
        this.listQuery.pageNum = 1
        this.getList()
      }
    },
    clearSearch() {
      this.listQuery = {
        pageNum: 1, // 页码
        pageRow: 20, // 每页条数
        order: undefined, // 排序字段
        sort: undefined, // 排序方式
        shidaima: '3701'
      }
    },
    clearBlank(row, column, cellValue) {
      if (cellValue !== null && cellValue !== '') {
        return cellValue
      }
      return '/'
    },
    formmatState(row, column, cellValue) {
      if (cellValue !== null && cellValue !== '') {
        switch (cellValue) {
          case '0':
            cellValue = '未检验'
            break
          case '1':
          case '2':
            cellValue = '检验中'
            break
          case '3':
          case '4':
            cellValue = '已检验'
            break
          default:
            cellValue = '未检验'
            break
        }
        return cellValue
      } // 0 未报检  1已报检  2 检验中  3 已检验  4 已登记0 领取
      return '/'
    },
    addToCart($index) {
      const base = this.list[$index]
      base.shebeidaima = base.shebeidaima === '' ? '/' : base.shebeidaima
      base.zhucedaima = base.zhucedaima === '' ? '/' : base.zhucedaima
      base.chanpinbianhao =
        base.chanpinbianhao === '' ? '/' : base.chanpinbianhao
      base.shiyongdengjibianhao =
        base.shiyongdengjibianhao === '' ? '/' : base.shiyongdengjibianhao
      if (this.shoppingCartData.length === 0) {
        this.shoppingCartData = [base]
      } else {
        for (let i = 0; i < this.shoppingCartData.length; i++) {
          if (base.id === this.shoppingCartData[i].id) {
            this.$message({
              message: '该设备已存在购物车中，请勿重复添加。',
              type: 'warning'
            })
            return false
          }
          if (base.shiyongdanwei !== this.shoppingCartData[i].shiyongdanwei) {
            this.$confirm('请确认“使用单位”是否同单位，是否继续？？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            })
              .then(() => {
                return true
              })
              .catch(() => {
                return false
              })
          }
          if (
            base.shebeizhongleidaima !==
            this.shoppingCartData[i].shebeizhongleidaima
          ) {
            this.$message('请选择同“种类设备”进行报检。')
            return false
          }
        }
        this.shoppingCartData.push(base)
      }
      this.shoppingSize++
    },
    clearCart() {
      this.shoppingCartData = []
      this.shoppingSize = 0
    },
    removeCart($index) {
      if ($index === 0) {
        this.shoppingCartData.splice($index, $index + 1)
      } else {
        this.shoppingCartData.splice($index, 1)
      }
      this.shoppingSize--
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleCartSelectionChange(val) {
      this.multipleCartSelection = val
    },
    insertCart() {
      for (let i = 0; i < this.multipleSelection.length; i++) {
        if (
          this.multipleSelection[0].shiyongdanwei !==
          this.multipleSelection[i].shiyongdanwei
        ) {
          this.$confirm('请确认“使用单位”是否同单位，是否继续？？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              return true
            })
            .catch(() => {
              return false
            })
        }
        if (
          this.multipleSelection[0].shebeizhongleidaima !==
          this.multipleSelection[i].shebeizhongleidaima
        ) {
          this.$message('请选择同“种类设备”进行报检。')
          return false
        }
      }
      if (this.shoppingCartData.length === 0) {
        this.shoppingCartData = this.multipleSelection
        this.shoppingSize += this.multipleSelection.length
      } else {
        const shoppingCartArray = []
        for (let j = 0; j < this.shoppingCartData.length; j++) {
          shoppingCartArray[j] = this.shoppingCartData[j].id
        }
        for (let i = 0; i < this.multipleSelection.length; i++) {
          if (shoppingCartArray.indexOf(this.multipleSelection[i].id) < 0) {
            this.shoppingCartData.push(this.multipleSelection[i])
            this.shoppingSize++
          }
        }
      }
    },
    checkSelection(row) {
      this.$refs.baseTable.toggleRowSelection(row)
    },
    checkCartSelection(row) {
      this.$refs.shoppingTable.toggleRowSelection(row)
    },
    convertBjd() {
      if (this.multipleSelection.length === 0) {
        this.$message('请在列表选择要生成的数据。')
        return false
      }
      let stateFlag = false
      let danweiFlag = false
      for (let i = 0; i < this.multipleSelection.length; i++) {
        if (
          this.multipleSelection[0].shebeizhongleidaima !==
          this.multipleSelection[i].shebeizhongleidaima
        ) {
          this.$message('请选择同“种类设备”进行报检。')
          return false
        }
        if (
          this.multipleSelection[i].state === '1' ||
          this.multipleSelection[i].state === '2'
        ) {
          // 只要是 1 跟 2 都要算 未完成设备
          stateFlag = true
        }
        if (
          this.multipleSelection[0].shiyongdanwei !==
          this.multipleSelection[i].shiyongdanwei
        ) {
          danweiFlag = true
        }
        // this.multipleSelection[i].baseId = '' // 此处将64的id替换掉 要不然保存会出错。
      }
      if (danweiFlag) {
        this.$confirm('请确认“使用单位”是否同单位，是否继续？？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            if (stateFlag) {
              this.$confirm(
                '设备中存在已报检未完成设备，是否继续？？',
                '提示',
                {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }
              ).then(() => {
                this.$router.push({
                  path:
                    '/bjd/bjd-dj-input/null/' +
                    this.multipleSelection[0].shebeizhongleidaima +
                    '/' +
                    this.multipleSelection[0].shebeizhonglei +
                    '/create',
                  query: { params: this.multipleSelection }
                })
              })
            } else {
              this.$router.push({
                path:
                  '/bjd/bjd-dj-input/null/' +
                  this.multipleSelection[0].shebeizhongleidaima +
                  '/' +
                  this.multipleSelection[0].shebeizhonglei +
                  '/create',
                query: { params: this.multipleSelection }
              })
            }
          })
          .catch(() => {
            return false
          })
      } else {
        this.$router.push({
          path:
            '/bjd/bjd-dj-input/null/' +
            this.multipleSelection[0].shebeizhongleidaima +
            '/' +
            this.multipleSelection[0].shebeizhonglei +
            '/create',
          query: { params: this.multipleSelection }
        })
      }
    },
    convertBjdByCart() {
      if (this.shoppingCartData.length === 0) {
        this.$message('请在列表选择数据。')
        return false
      }
      for (let i = 0; i < this.multipleSelection.length; i++) {
        if (
          this.multipleSelection[0].shiyongdanwei !==
          this.multipleSelection[i].shiyongdanwei
        ) {
          this.$confirm('请确认“使用单位”是否同单位，是否继续？？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              return true
            })
            .catch(() => {
              return false
            })
        }
        if (
          this.multipleSelection[0].shebeizhongleidaima !==
          this.multipleSelection[i].shebeizhongleidaima
        ) {
          this.$message('请选择同“种类设备”进行报检。')
          return false
        }
      }
      const sbzldm = this.shoppingCartData[0].shebeizhongleidaima
      const sbzl = this.shoppingCartData[0].shebeizhonglei
      const bjBase = this.shoppingCartData
      this.$router.push({
        path: '/bjd/bjd-dj-input/null/' + sbzldm + '/' + sbzl + '/create',
        query: { params: bjBase }
      })
    },
    tableRowClassName({ row, rowIndex }) {
      console.log(row, rowIndex)
      // row.index = rowIndex
      const nextTime = new Date(row.xiacijianyanriqi).getTime()
      const currentTime = new Date().getTime()
      console.log(nextTime, currentTime, nextTime - currentTime)
      if (nextTime - currentTime < 7776000000) {
        console.log('<3')
        return 'restart-row'
      } else if (nextTime - currentTime >= 7776000000) {
        return 'reject-row'
      }
      return ''
    }
  }
}
</script>
<style>
.root .el-table .reject-row {
  background: #e6a23c;
}
.root .el-table .restart-row {
  background: #f56c6c;
}
.tips1 {
  background: #e6a23c;
  color: #ffffff;
  width: 70px;
  height: 30px;
  border-radius: 5px;
  float: left;
  margin-right: 20px;
  font-size: 14px;
  text-align: center;
  line-height: 30px;
}
.tips2 {
  background: #f56c6c;
  color: #ffffff;
  width: 70px;
  height: 30px;
  font-size: 14px;
  text-align: center;
  border-radius: 5px;
  float: left;
  line-height: 30px;
}
.uFlex {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}
.mt-10 {
  margin-top: 10px;
}
</style>
