<template>
  <div>
    <FullPage title='测量订单列表'
              :list='set_list'
              @init='init'
              :loading='loading'
              @searchData='searchData'
              @selectTable='selectTable'
              @changePage='changePage'
              @changeSize='changeSize'
              :tableColums='tableColums'
              :showPage='false'
              :tableData='tableData'
              :page_index='page_index'
              :total='total'>
      <div slot='titleButton'
           style="display:flex;">
        <Upload v-if='persimissionData["批量导入"]||persimissionData.all'
                name='your_file'
                :show-upload-list='false'
                :headers='headers'
                :on-error='uploadError'
                :on-success='uploadSuccess'
                :action="$store.state.ip+'/api/measure_orders_import'">
          <Button type="success"
                  ghost
                  icon='md-exit'
                  style="margin-right:10px;">批量导入</Button>
        </Upload>
        <Button v-if='persimissionData["批量导出"]||persimissionData.all'
                @click="exportData"
                type="warning"
                ghost
                icon='md-return-left'
                style="margin-right:10px;">批量导出</Button>
        <Button @click="openModal(selects)"
                v-if='persimissionData["批量下生产"]||persimissionData.all'
                type="primary"
                ghost>批量下生产</Button>
      </div>
      <div slot='navButton'
           style="display:flex;">
        <Button v-if='persimissionData["表头设置"]||persimissionData.all'
                @click="setupTableHeader"
                type="primary"
                ghost
                icon='ios-cog'>表头设置</Button>
      </div>
      <template slot="basicTypeSet"
                slot-scope="{row}">
        <div>
          <span v-for="item in warningList"
                :key="item.id"
                :style="{color:item.color}"
                v-show="item.id==row.warning_state">{{item.title}}</span>
        </div>
      </template>
      <template slot='set'
                slot-scope='{row}'>
        <div>
          <a v-if='persimissionData["编辑"]||persimissionData.all'
             style="margin:0 5px"
             @click="goPage(row,0)">编辑</a>
          <a v-if='persimissionData["查看"]||persimissionData.all'
             style="margin:0 5px"
             @click="goPage(row,1)">查看</a>
          <a v-if='persimissionData["下生产"]||persimissionData.all'
             style="margin:0 5px"
             v-show="row.state<3"
             @click="openModal(row)">下生产</a>
        </div>
      </template>
      <template slot="pageSlot">
        <div class="pageSlotStyle">
          <Page :page-size-opts="[10, 20, 30, 40,100,1000]"
                @on-page-size-change='changeSize'
                @on-change='changePage'
                :current='page_index'
                show-total
                :total="total"
                show-sizer
                :page-size='page_size' />
        </div>
      </template>
    </FullPage>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  data () {
    return {
      tableColums: [
        { type: 'selection', fixed: 'left', title: '全选', key: 'selection', width: 90, align: 'center' },
        { title: '订单编号', align: 'center', key: 'order_no', width: '200' },
        {
          title: '测量状态', align: 'center', key: 'state', minWidth: 150,
          render: (h, params) => h('span', {},
            params.row.state == 0 ? '测量未审核'
              : (params.row.state == 1 ? '测量审核'
                : (params.row.state == 2 ? '测量中'
                  : (params.row.state == 3 ? '生产审核中'
                    : (params.row.state == 4 ? '生产通过'
                      : (params.row.state == 5 ? '到生产计划' : '完成')))))
          )
        },
        {
          title: '测量单号', align: 'center', key: 'oa_order_no', minWidth: 200,
          render: (h, params) => h('span', {}, params.row.oa_order_no || params.row.order_no)
        },
        {
          title: '测量确认率', align: 'center', minWidth: 150, key: 'measure_rate',
          render: (h, params) => h('span', {}, (((params.row.measure_rate * 1).toFixed(2)) * 100) + '%')
        },
        { title: '紧急程度', align: 'center', key: 'warning_state', minWidth: 100, slot: 'basicTypeSet', },
        { title: '项目名称', align: 'center', key: 'residential_name', minWidth: 200 },
        { title: '地址', align: 'center', key: 'address', minWidth: 200 },
        { title: '客户姓名', align: 'center', key: 'client_name', minWidth: 100 },
        { title: '电话', align: 'center', key: 'mobile', minWidth: 150 },
        // {
        //   title: '订单类型', align: 'center', key: 'order_type', minWidth: 100,
        //   render: (h, params) => h('span', {}, params.row.order_type == 1 ? '工装' : '家装')
        // },
        {
          title: '测量开始时间', align: 'center', minWidth: 200, key: 'measure_start_time',
          render: (h, params) => h('span', {}, this.func.replaceDate(params.row.measure_start_time * 1, 1))
        },
        {
          title: '测量结束时间', align: 'center', minWidth: 200, key: 'measure_end_time',
          render: (h, params) => h('span', {}, this.func.replaceDate(params.row.measure_end_time * 1, 1))
        },
        {
          title: '实际完成时间', align: 'center', minWidth: 200, key: 'measure_time',
          render: (h, params) => h('span', {}, params.row.measure_time ? this.func.replaceDate(params.row.measure_time * 1) : '')
        },
        {
          title: '订单状态', align: 'center', minWidth: 100, key: 'sub_state',
          render: (h, params) => h('span', {}, params.row.sub_state == 0 ? '测量未审核' : (params.row.sub_state == 1 ? '测量审核' :
            (params.row.sub_state == 2 ? '测量通过' : (params.row.sub_state == 3 ? '生产审核中' : (params.row.sub_state == 4 ? '生产通过' : '到生产计划')))))
        },
        { title: '备注', align: 'center', key: 'remark', minWidth: 200 },
        { title: '操作', align: 'center', key: 'set', slot: 'set', width: '200', fixed: 'right' },
      ],
      tableData: [],
      page_index: 1,
      page_size: 10,
      total: 0,
      proxyObj: {},
      planInfo: {
        order_no: null,
        start_time: '',
        end_time: ''
      },
      loading: false,
      headers: { 'Authorization': localStorage.getItem('token') },
      selects: [],
      tableheaders: [],
      //详情页返回保留搜索数据
      corssPageData: localStorage.getItem('corssPageData') ? JSON.parse(localStorage.getItem('corssPageData')) : {},
      warningList: []
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      if (from.path != '/cms/measurementordermannage/edit') {
        localStorage.removeItem('corssPageData')
      } else {
        vm.firstEnter = 1
      }
    });
  },
  beforeRouteLeave (to, from, next) {
    if (to.path == '/cms/measurementordermannage/edit') {
      this.corssPageData.page_index = this.page_index,
        this.corssPageData.page_size = this.page_size,
        localStorage.setItem('corssPageData', JSON.stringify(this.corssPageData))
    } else {
      localStorage.removeItem('corssPageData')
    }
    next(vm => {
    });
  },
  created () {
    // 获取紧急程度
    this.axios.get('/api/warning_list').then(res => { this.warningList = res.data.data })
  },
  computed: {
    ...mapState(['persimissionData']),
    computedTable () {
      // if (this.tableheaders.length < 1) {
      return this.tableColums
      // }
      // return this.func.computedHeader(this.tableheaders, this.tableColums)
    },
    set_list () {
      return [
        { title: '订单编号', serverName: 'order_no', name: 'Input', value: '', placeholder: '请输入订单号' },
        {
          title: '紧急程度', name: 'Select', serverName: 'warning_state', optionValue: 'id', optionName: 'title', placeholder: '请选择', value: this.corssPageData ? this.corssPageData.warning_state : '',
          option: this.warningList
        },
        {
          title: '测量状态', name: 'Select', placeholder: '请选择', serverName: 'state', value: '',
          option: [
            { label: '全部', value: 99 },
            { label: '未测量', value: 3 },
            { label: '测量中', value: 2 },
            { label: '测量完成', value: 1 },
          ]
        },
        { title: '测量日期范围', start_server: 'start_time', end_server: 'end_time', start_value: '', end_value: this.corssPageData ? this.corssPageData.end_value : '', isDate: true, start_placeholder: '开始日期', end_placeholder: '结束日期' },
        { title: '测量单号', serverName: 'order_no', name: 'Input', value: '', placeholder: '请输入测量单号' },
        { title: '项目名称', serverName: 'residential_name', name: 'Input', value: '', placeholder: '请输入项目名称' },
        { title: '客户姓名', serverName: 'client_name', name: 'Input', value: '', placeholder: '请输入客户姓名' },
        {
          title: '订单状态', name: 'Select', placeholder: '请选择', serverName: 'sub_state', value: '',
          option: [
            { label: '全部', value: 0 },
            { label: '测量未审核', value: 1 },
            { label: '测量审核', value: 2 },
            { label: '测量通过', value: 3 },
            { label: '生产审核中', value: 4 },
            { label: '生产通过', value: 5 },
            { label: '到生产计划', value: 6 },
            { label: '完成', value: 7 },
          ]
        },
        // { title: '测量状态', serverName: 'order_no', name: 'Input', value: '', placeholder: '请输入测量状态' },
      ]
    }
  },
  methods: {
    init (row) {
      // row.page_index = this.page_index;
      // row.page_size = this.page_size;
      row.sub_state = 2;
      if (this.firstEnter == 1) {
        this.corssPageData = JSON.parse(localStorage.getItem('corssPageData'))
        row = this.corssPageData
        this.proxyObj = row
        this.searchData(row)
      } else {
        this.page_index = 1
        row.page_index = this.page_index;
        row.page_size = this.page_size;
        this.proxyObj = row
        this.getData(row)
      }
    },
    searchData (row) {
      if (this.firstEnter == 1) {
        this.page_index = this.corssPageData.page_index;
        this.page_size = this.corssPageData.page_size;
        this.set_list[0].value = this.corssPageData.order_no
        this.set_list[1].value = this.corssPageData.warning_state
        this.set_list[2].value = this.corssPageData.state
        this.set_list[3].start_value = this.corssPageData.start_time ? this.corssPageData.start_time : ''
        this.set_list[3].end_value = this.corssPageData.end_time ? this.corssPageData.end_time : ''
        this.corssPageData.type = this.$route.query.type
        this.getData(this.corssPageData)
      } else {
        this.page_index = 1
        row.page_index = this.page_index;
        row.page_size = this.page_size;
        this.corssPageData.order_no = this.set_list[0].value
        this.corssPageData.warning_state = this.set_list[1].value
        this.corssPageData.state = this.set_list[2].value
        this.corssPageData.start_time = this.func.setDate(this.set_list[3].start_value)
        this.corssPageData.end_time = this.func.setDate(this.set_list[3].end_value)
        this.proxyObj = row
        this.getData(row)
      }
    },
    getData (row) {
      this.loading = true;
      this.axios('/api/order_measure_list', { params: row }).then(res => {
        this.loading = false;
        this.firstEnter++
        this.tableData = res.data.data;
        this.total = res.data.total;
        this.tableheaders = res.data.tableSet || []
      })
    },
    changePage (e) {
      this.page_index = e;
      this.proxyObj.page_index = this.page_index;
      this.getData(this.proxyObj)
    },
    changeSize (e) {
      this.page_size = e;
      this.proxyObj.page_size = this.page_size;
      this.getData(this.proxyObj)
    },
    goPage (row, s) {
      const order_no = row ? row.id : '';
      const id = row ? row.id : ''
      this.$router.push({
        path: '/cms/measurementordermannage/edit',
        // path:'/cms/ordermannage/businessorderlist/decorationlist',
        query: {
          id: id,
          order_no: row.order_no,
          type: 'measure',
          editType: s ? 1 : 0
        }
      })
    },
    approvalDetails (row) {
      this.$router.push({
        path: '/cms/approval/examine',
        query: {
          order_no: row.oa_order_no || row.order_no
        }
      })
    },
    openModal (row) {
      if (Array.isArray(row)) {
        if (row.length < 1) { return this.$Message.warning('请选择一项') }
        this.planInfo.order_no = row.reduce((pre, cur, idx) => `${pre}${cur.order_no}${idx == row.length - 1 ? '' : ','}`, '')
      } else {
        this.planInfo.order_no = row.order_no;
      }
      this.downProduction({
        title: '下生产',
        type: 2,
        params: this.planInfo,
        then: (e) => { this.getData(this.proxyObj) },
        cancel: (e) => { },
      })
    },
    async exportData () {
      const res = await this.axios('/api/measure_orders_export', { params: { ...this.proxyObj } })
      if (res.code == 200) {
        let url = `${this.$store.state.ip}/api/storage/${res.data.file}`
        location.href = url
      }
    },
    uploadSuccess (res) {
      if (res.code == 200) {
        this.$Message.success(res.msg || '上传成功')
      } else {
        this.$Message.warning(res.msg || '上传失败')
      }
      this.getData(this.proxyObj)
    },
    uploadError (err) {
      this.$Message.error(err.msg || '上传失败')
    },
    selectTable (e) {
      this.selects = e;
    },
    setupTableHeader () {
      this.tableheaders.length < 1 ? this.tableheaders = this.tableColums.reduce((pre, cur) => pre.concat(cur.key), []) : ''
      this.$setTableheader({
        list: this.tableColums,
        selects: this.tableheaders,
        then: (result) => {
          this.tableheaders = result
          this.axios.post('/api/update/table', { id: this.$route.query.id, result }).then(res => {
            if (res.code == 200) {
              this.$Message.success(res.msg)
            }
          })
        }
      })
    },
  }
}
</script>

<style lang="scss" scoped>
.nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.item-attr {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.pageSlotStyle {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}
</style>