<template>
  <view class="content">
	<view class="navbar--fixed" style="background-color: white;">
	<uni-status-bar></uni-status-bar>
	<view style="display: flex;width: 750rpx;height: 44px;align-items: center;justify-content: space-between;padding: 0rpx 24rpx;">
		<view class="select-area">
		  <qn-select options-align="left" :contentStyle="contentStyle" :options="factoryList" v-model="factoryId" placeholder="请选择工厂" hasOperation>
		    <template #operation>
		      <view class="operation" @click.stop="manageFactory">
		        <text>工厂管理</text>
		        <image class="icon" src="/static/imgs/digital-workshops/operation-icon.png"></image>
		      </view>
		    </template>
		  </qn-select>
		</view>
		<view style="width: 240rpx;">
		  <uni-segmented-control :current="current" :values="['设备', '订单']" @clickItem="onClickItem" styleType="button"></uni-segmented-control>
		</view>
	</view>
	</view>
	<view class="uni-navbar__placeholder">
		<uni-status-bar></uni-status-bar>
		<view style="height: 44px" />
	</view>
	<view class="flex-col" style="flex-grow: 1;overflow: hidden;" v-show="current == 0">
	  <view class="flex-col section_3">
	    <view class="flex-row group_2" style="flex: 1;">
	      <view class="text-wrapper" :class="{ 'text-wrapper_selected': curTab === key }" v-for="(value, key) in listObj" :key="key" @click="selectTab(key)">
	        <text v-if="key != 'null'">{{ key }}</text>
	        <view v-show="curTab === key" class="divider"></view>
	      </view>
		  <!-- <view style="display: flex;align-items: center;justify-content:flex-end;flex: 1;">
			  <uni-icons type="plusempty" size="28" @click="addDevice"></uni-icons>
		  </view> -->
	    </view>
	  </view>
	  <view class="bottom-group flex-col">
	    <view class="flex-row section_5">
	      <view class="flex-row group_3" v-for="(value, key) in listObj[curTab].type" :key="key">
	        <view class="group_4">
	          <text class="text_5">{{ key }}(</text>
	          <text class="text_7">{{ value[0] }}</text>
	          <!-- <text class="text_5">/</text>
	          <text class="text_11">{{ value[1] }}</text> -->
	          <text class="text_5">)</text>
	        </view>
	      </view>
	      <view v-if="!listObj['所有设备'].list || listObj['所有设备'].list.length == 0" class="flex-row-center-center empty_1">
	        <text>设备列表为空</text>
	      </view>
	    </view>
	    <view class="flex-col section_8" v-if="cameraList && cameraList.length > 0">
	      <view class="justify-between group_11" @click="go2('camera-list', { id: factoryId })">
			<view class="flex-row-center-center">
			  <image src="/static/imgs/digital-workshops/camera-icon.png" style="height: 32rpx;width: 32rpx;" />
	          <text style="margin-left: 8rpx;">摄像机({{ cameraList.length }}台)</text>
			</view>
	        <image src="/static/imgs/digital-workshops/right-arrow-icon.png" class="image_1" />
	      </view>
	      <view class="flex-col items-center group_12">
	        <!-- <image src="/static/imgs/digital-workshops/camera-tip-bg.png" class="image_2" @click="go2('video-play', { url: cameraList[0].videoUrl })" />
	        <text class="text_18">{{ cameraList[0].address }}</text> -->
			<video :src="cameraList[0].hlsUrl" autoplay class="image_2"></video>
	      </view>
	    </view>
	    <view class="flex-col section_9">
	      <!-- <view class="justify-between sticky">
	        <text class="text_19">设备列表</text>
	        <view class="flex-row group_14" v-if="!isExample" @click="addDevice">
	          <text>新增</text>
	          <image src="/static/imgs/digital-workshops/add-icon.png" class="image_4" />
	        </view>
	      </view> -->
	      <view class="list-area">
	        <view v-if="listObj[curTab].list && listObj[curTab].list.length > 0">
	          <DeviceItem v-for="item in listObj[curTab].list" :key="item.id" :deviceInfo="item" style="margin-bottom: 20rpx" @click="jump"></DeviceItem>
	        </view>
	        <view v-else>
	          <view class="flex-col group_9">
	            <view class="flex-col items-center group_10">
	              <view class="flex-col items-center image-wrapper">
	                <image src="/static/imgs/digital-workshops/empty-list.png" class="image_5" />
	              </view>
	              <text class="text_10">设备列表为空</text>
	            </view>
	            <!-- <view class="flex-col items-center text-wrapper_4" @click="addDevice">
	              <text>添加设备</text>
	            </view> -->
	          </view>
	        </view>
	      </view>
	    </view>
	  </view>
	</view>
	<view style="flex-grow: 1;overflow: hidden;" v-show="current == 1">
		<view class="status-bar">
		  <view v-for="item in statusBarArray" :key="item.value" :class="{ box: true, 'box--selected': condition.status == item.value }" @click="selectStatus(item.value)">
		    {{ item.label }}
		  </view>
		</view>
		<view class="list-area">
		  <scroll-list ref="list" :option="option" @load="upCallback" @refresh="downCallback">
			<OrderItem v-for="(item, index) in list" :key="item.id" :item="item" :index="index" @click="goDetail"></OrderItem>
		  </scroll-list>
		</view>
	</view>

  </view>
</template>

<script>
import { go2, back } from '@/utils/hook.js'
import DeviceItem from './DeviceItem'
import OrderItem from './OrderItem'
import { deviceStatus, orderStatusList, orderStatusEnum, StatusMap } from '@/enums/index'
import { getCameraListApi, getMyFactoryList, getMachinList } from '@/apis/factoryApi'
import { dateTimeFormat } from '@/utils/index.js'
import { getProdOrderList } from '@/apis/orderApi.js'
import http from '@/utils/http/index.js'

export default {
  components: {
    DeviceItem,
	OrderItem
  },
  data() {
    return {
      contentStyle: 'background: none; padding: 0;text-align: right;font-size: 34rpx;',
      factoryId: null,
      isExample: false,
      listObj: {
        所有设备: {
          type: {},
          list: []
        }
      },
      curTab: '所有设备',
      factoryList: [],
      deviceList: [],
      workShopList: [
        {
          label: '所有设备',
          value: 0
        },
        {
          label: '1楼车间',
          value: 1
        }
      ],
      deviceTypeList: [
        { id: 1, name: '印刷机', working: 1, free: 1 },
        { id: 2, name: '模切机', working: 1, free: 1 },
        { id: 3, name: '覆膜机', working: 1, free: 1 }
      ],
      cameraList: [],
      hasCompany: this.$store.state.companyInfo.id,
	  current: 0,
	  condition: {
	    status: -2,
	    pageNum: 0, // 初始会执行一次下拉加载
	    pageSize: 30
	  },
	  option: {
	    size: 10,
	    auto: true,
	    emptyText: '暂无订单~',
	    background: '#F7F8FA',
	    emptyImage: '/static/imgs/order/order-empty.png'
	  },
	  list: [],
	  statusBarArray: orderStatusList,
	  orderStatusMap: Object.freeze(StatusMap)
    }
  },
  onLoad() {
    this.getFactoryList()
  },
  onPullDownRefresh() {
    this.getFactoryList()
    uni.stopPullDownRefresh()
  },
  watch: {
    factoryId(val, oldVal) {
      this.getCameraList()
      this.getList()
	  this.upCallback()
      this.isExample = this.factoryList.find((factory) => factory.value == val).isExample
    },
    refresh(val) {
      console.log('refresh', val)
      if (val) {
      }
    }
  },
  computed: {
    refresh() {
      if (this.$store.state.userInfo.userId) {
        this.getFactoryList()
      }
    }
  },
  methods: {
    jump(item) {
      // go2('device-production-info', { id: item.id })
    },
    go2,
    back,
    selectTab(index) {
      this.curTab = index
    },
	onClickItem(e) {
	    if (this.current != e.currentIndex) {
	       this.current = e.currentIndex;
	    }
	},
    getList() {
      getMachinList({ factoryId: this.factoryId, pageSize: 1000 }).then((res) => {
        let list = res.records
        let data = { 所有设备: { name: '所有设备', type: {}, list: [] } }
        for (let i = 0; i < list.length; i++) {
          let position = list[i].position
          if (position) {
            if (!data[position]) {
              data[position] = {
                name: position,
                list: [],
                type: {}
              }
            }
            data[position].list.push(list[i])
            data['所有设备'].list.push(list[i])
            // 0 工作中 1 空闲中
            if (!data[position].type[list[i].typeName]) {
              data[position].type[list[i].typeName] = [0, 0]
            }
            if (!data['所有设备'].type[list[i].typeName]) {
              data['所有设备'].type[list[i].typeName] = [0, 0]
            }
            // if (list[i].workingStatus === deviceStatus.WORKING) {
            //   data[position].type[list[i].typeName][0]++
            //   data['所有设备'].type[list[i].typeName][0]++
            // }
            // if (list[i].workingStatus === deviceStatus.FREE) {
            //   data[position].type[list[i].typeName][1]++
            //   data['所有设备'].type[list[i].typeName][1]++
            // }
			data[position].type[list[i].typeName][0]++
			data['所有设备'].type[list[i].typeName][0]++
          } else {
            data['所有设备'].list.push(list[i])
            // 0 工作中 1 空闲中
            if (!data['所有设备'].type[list[i].typeName]) {
              data['所有设备'].type[list[i].typeName] = [0, 0]
            }
            // if (list[i].workingStatus === deviceStatus.WORKING) {
            //   data['所有设备'].type[list[i].typeName][0]++
            // }
            // if (list[i].workingStatus === deviceStatus.FREE) {
            //   data['所有设备'].type[list[i].typeName][1]++
            // }
			 data['所有设备'].type[list[i].typeName][0]++
          }
		  
		  data['所有设备'].list.push(list[i])
        }
        this.listObj = data
      }).catch(err => {
        console.log(err)    
	  })
    },
    companyTip() {
      if (!this.hasCompany) {
        uni.showModal({
          title: '提示',
          content: '您还没有企业，请前往完善企业信息',
          success: (res) => {
            if (res.confirm) {
              go2('enterprise-info')
            }
          }
        })
        return true
      }
      return false
    },
    manageFactory() {
      if (this.companyTip()) {
        return
      }
      go2('factory-manage')
    },
    addDevice() {
      if (this.companyTip()) {
        return
      }
      // 先判断是否时演示工厂
      go2('device-operation', { factoryId: this.factoryId, operation: 'add' })
    },
    // 获取摄像头列表
    getCameraList() {
      // getCameraListApi({ factoryId: this.factoryId }).then((res) => {
      //   this.cameraList = res
      // })
	  var url = `https://api-ops-yyt.qniao.cn/cloud-print-cloud-factory/user/get/factory/video-machine/list?factoryId=${this.factoryId}`
	  http.get({ url }).then(res => {
		if(res){
		    this.cameraList = res
		}		
	  })
    },
    // 获取工厂列表
    getFactoryList() {
      getMyFactoryList().then((res) => {
        this.factoryList = res.map((item) => {
          return {
            label: item.name,
            value: item.id,
            isExample: item.name == '演示样板工厂'
          }
        })
        if (this.factoryId == this.factoryList[0].value) {
          this.getCameraList()
          this.getList()
        }
        this.factoryId = this.factoryList[0].value
      })
    },
	dateTimeFormat,
	fetchOrderList() {
	  return new Promise((resolve, reject) => {
	    getProdOrderList({ ...this.condition, status: this.condition.status == -2 ? '' : this.condition.status })
	      .then((res) => {
	        if (res) {
			  var rspList = []
			  for (var i = 0; i < res.records.length; i++) {
			  	const item = res.records[i]
				if(item.productInfoList && item.productInfoList.length){
					rspList.push(item)
				}
			  }
	          if (this.condition.pageNum == 1) {
	            this.list = rspList
	          } else {
	            this.list = this.list.concat(rspList)
	          }
	          resolve({ list: this.list, total: rspList.length })
	        } else {
	          reject()
	        }
	      })
	      .catch((err) => {
	        reject(err)
	      })
	  })
	},
	downCallback() {
	  this.condition.pageNum = 1
	  this.fetchOrderList()
	    .then(({ list, total }) => {
	      this.$refs.list.refreshSuccess({ list, total })
	    })
	    .catch(() => {
	      this.$refs.list.refreshFail()
	    })
	},
	upCallback(page) {
	  this.condition.pageNum++
	  this.fetchOrderList()
	    .then(({ list, total }) => {
	      this.$refs.list.loadSuccess({ list, total })
	    })
	    .catch(() => {
	      this.$refs.list.loadFail()
	    })
	},
	selectStatus(status) {
	  this.condition.status = status
	  this.downCallback()
	},
	transformTarget(target) {
	  let result = ''
	  if (target.categoryName) {
	    result += `${target.categoryName}`
	  }
	  if (target.brandName) {
	    result += `/${target.brandName}`
	  }
	  if (target.gramWeight) {
	    result += `/${target.gramWeight}g`
	  }
	  if (target.length && target.width) {
	    result += `/${target.width}*${target.length}`
	  }
	  if (target.pieceQuantity) {
	    result += `/${target.pieceQuantity}张`
	  }
	  return result
	},
	// 根据状态跳转到不同页面
	goDetail(order) {
	  go2('order-info', { orderId: order.id })
	}
  }
}
</script>

<style lang="scss" scoped>
	
	.navbar--fixed {
		position: fixed;
		z-index: 998;
		/* #ifdef H5 */
		left: var(--window-left);
		right: var(--window-right);
		/* #endif */
		/* #ifndef H5 */
		left:0;
		right: 0;
		/* #endif */
	
	}
.content {
  width: 750rpx;
  height: calc(100vh-50px);
  display: flex;
  flex-direction: column;
  flex: 1;
}
.select-area {
  max-width: 400rpx;
  .operation {
    height: 60rpx;
    line-height: 60rpx;
    color: rgb(0, 0, 0);
    font-size: 28rpx;
    padding: 0 24rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1rpx solid #f5f5f5;
    .icon {
      width: 32rpx;
      height: 32rpx;
    }
  }
}
.section_3 {
    padding-bottom: 3rpx;
    background-color: rgb(255, 255, 255);
    .group_2 {
      padding: 0 32rpx;
      width: 100%;
      overflow-x: auto;
      border-bottom: solid 2rpx rgb(221, 221, 221);
      .text-wrapper {
        color: rgb(136, 136, 136);
        font-size: 28rpx;
        height: 80rpx;
        line-height: 80rpx;
        white-space: nowrap;
        position: relative;
        text-align: center;
        margin-right: 40rpx;
        min-width: 80rpx;
      }
      .text-wrapper_selected {
        color: rgb(51, 51, 51);
        font-weight: 500;
      }
      .divider {
        background-color: rgb(0, 122, 255);
        border-radius: 3rpx;
        width: 80rpx;
        height: 6rpx;
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
      }
    }
  }
  
  .bottom-group {
    padding-bottom: 20rpx;
    .section_5 {
      padding: 12rpx 32rpx 0;
      background-color: rgb(255, 255, 255);
      flex-wrap: wrap;
      .group_3 {
        flex: 0 0 auto;
        align-items: flex-start;
        margin-right: 12rpx;
        margin-bottom: 16rpx;
        .group_4 {
          white-space: nowrap;
          height: 40rpx;
          .text_5 {
            color: rgb(31, 31, 31);
            font-size: 28rpx;
            line-height: 40rpx;
          }
          .text_7 {
            color: rgb(82, 196, 26);
            font-size: 28rpx;
            line-height: 40rpx;
          }
          .text_11 {
            color: rgb(255, 72, 73);
            font-size: 28rpx;
            line-height: 40rpx;
          }
        }
      }
      .empty_1 {
        height: 100rpx;
        width: 686rpx;
        color: rgb(0, 0, 0);
        font-size: 28rpx;
        font-weight: 500;
        line-height: 40rpx;
      }
      .grid-item {
        color: rgb(133, 133, 133);
        font-size: 24rpx;
        line-height: 33rpx;
        white-space: nowrap;
        .left-section {
          align-self: center;
          background-color: rgb(82, 196, 26);
          border-radius: 50%;
          width: 8rpx;
          height: 8rpx;
          margin-right: 4rpx;
        }
        .red {
          background-color: rgb(255, 72, 73);
        }
      }
    }
    .section_8 {
      margin-top: 20rpx;
      padding: 0 32rpx 33rpx;
      background-color: rgb(255, 255, 255);
      .group_11 {
        padding: 19rpx 0;
        color: rgb(51, 51, 51);
        font-size: 36rpx;
        font-weight: 500;
        line-height: 50rpx;
        white-space: nowrap;
        .image_1 {
          margin-right: 9rpx;
          align-self: center;
          width: 14rpx;
          height: 24rpx;
        }
      }
      .group_12 {
        color: rgb(255, 255, 255);
        font-size: 28rpx;
        font-weight: 500;
        line-height: 40rpx;
        white-space: nowrap;
        position: relative;
        .image_2 {
          width: 91.5vw;
          height: 51.5vw;
        }
        .text_18 {
          position: absolute;
          left: 24rpx;
          top: 16rpx;
        }
      }
    }
    .section_9 {
      margin-top: 20rpx;
      padding: 0 24rpx 32rpx 24rpx;
      .sticky {
        position: sticky;
        top: 0;
        z-index: 10;
        background: white;
        padding: 30rpx 0 20rpx;
      }
      .text_19 {
        color: rgb(51, 51, 51);
        font-size: 36rpx;
        font-weight: 500;
        line-height: 50rpx;
        white-space: nowrap;
      }
      .group_14 {
        margin: 5rpx 0;
        color: rgb(0, 122, 255);
        font-size: 28rpx;
        font-weight: 500;
        line-height: 40rpx;
        white-space: nowrap;
        .image_4 {
          margin: 4rpx 0 4rpx 10rpx;
          width: 32rpx;
          height: 32rpx;
        }
      }
      .list-area {
        padding-bottom: 40rpx;
      }
      .group_9 {
        margin-top: 39rpx;
        .group_10 {
          padding-bottom: 28rpx;
          color: rgb(0, 0, 0);
          font-size: 28rpx;
          font-weight: 500;
          line-height: 40rpx;
          white-space: nowrap;
          position: relative;
          .image-wrapper {
            width: 280rpx;
            .image_5 {
              width: 280rpx;
              height: 366rpx;
            }
          }
          .text_10 {
            position: absolute;
            bottom: 8rpx;
            left: 50%;
            transform: translateX(-50%);
          }
        }
        .text-wrapper_4 {
          padding: 16rpx 0;
          align-self: center;
          color: rgb(0, 122, 255);
          font-size: 32rpx;
          font-weight: 500;
          line-height: 45rpx;
          white-space: nowrap;
          border-radius: 40rpx;
          width: 200rpx;
          border: solid 2rpx rgb(0, 122, 255);
        }
      }
    }
  }

.status-bar {
    flex-grow: 0;
    flex-shrink: 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 32rpx;
    border-bottom: 2rpx solid #f8f8f8;
    background-color: #fff;
    height: 90rpx;
    .box {
      height: 86rpx;
      flex-grow: 0;
      flex-shrink: 0;
      color: #000000;
      font-size: 28rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      border-bottom: 4rpx solid #ffffff;
    }
    .box--selected {
      border-bottom: 4rpx solid #007aff;
      color: #007aff;
    }
  }
  
  .list-area {
    flex-grow: 1;
    overflow: hidden;
    .order-area {
      width: 750rpx;
      margin-bottom: 20rpx;
      background-color: #fff;
      .order-header {
        display: flex;
        align-items: flex-start;
        justify-content: space-between;
        padding: 18rpx 32rpx;
        border-bottom: 2rpx solid #f8f8f8;
        .left {
          display: flex;
          flex-direction: column;
          align-items: flex-start;
          justify-content: flex-start;
        }
      }
      .order-content {
        border-bottom: 2rpx solid #f8f8f8;
        .header {
          display: flex;
          align-items: flex-start;
          justify-content: space-between;
          padding: 24rpx 32rpx;
          border-bottom: 2rpx solid #f8f8f8;
        }
        .order-item {
          display: flex;
          align-items: center;
          justify-content: flex-start;
          width: 686rpx;
          margin: 24rpx 32rpx;
          .img {
            width: 100rpx;
            height: 100rpx;
            margin-right: 20rpx;
            flex-grow: 0;
            flex-shrink: 0;
          }
          .right {
            display: flex;
            flex-direction: column;
            align-items: flex-start;
            justify-content: flex-start;
          }
        }
        .border {
          border-top: 2rpx solid #f8f8f8;
        }
      }
      .order-footer {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 24rpx 32rpx;
        border-bottom: 2rpx solid #f8f8f8;
        .left {
          display: flex;
          flex-direction: row;
          align-items: center;
          justify-content: flex-start;
        }
        .right {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: flex-end;
        }
      }
    }
  }

</style>
