<template>
  <div style="width: 100%; height: 100%; position: relative">
    <!-- 工单池 -->
    <template-page
      v-if="!(!!~['detail'].indexOf(pageType) && pageCode != '') && showTableBool"
      ref="pageRef"
      :getList="getList"
      :operation="operation()"
      :exportList="exportList"
      :optionsEvensGroup="optionsEvensGroup"
      :columnParsing="columnParsing"
      :tableAttributes="tableAttributes"
      :tableEvents="tableEvents"
      :moreParameters="moreParameters"
      :screeningAnalysis="screeningAnalysis"
      :filterMethod="filterMethod"
      :replaceOrNotMap="true"
      :defaultSearchData="defaultSearchData"
    >
      <div slot="moreSearch">
        <div style="margin-bottom: 10px">
          <span
            style="
              font-size: 12px;
              font-weight: 400;
              text-align: left;
              color: #666;
              line-height: 28px;
              margin-right: 10px;
            "
            >选择年份</span
          >
          <el-date-picker
            style="width: 130px"
            v-model="value1"
            format="yyyy"
            size="mini"
            type="year"
            placeholder="选择日期"
          >
          </el-date-picker>
        </div>
      </div>
      <!-- 创建工单 -->
      <div class="cartographer_big" v-if="!(!!~['detail'].indexOf(pageType) && pageCode != '')">
        <el-dialog
          title="创建工单"
          width="100%"
          :modal="false"
          :visible.sync="createFormBool"
          :before-close="handleClose"
        >
          <workOrderInfo :workOrderType="workOrderType" v-if="createFormBool" :cloneWorkOrder="cloneWorkOrder" />
        </el-dialog>
      </div>
      <!-- 批量预约/改约 -->
      <div class="cartographer_big" v-if="!(!!~['detail'].indexOf(pageType) && pageCode != '')">
        <el-dialog
          title="批量约单"
          width="100%"
          :modal="false"
          :visible.sync="rescheduleBool"
          :before-close="rescheduleClose"
        >
          <Reschedule v-if="rescheduleBool" :recordSelected="recordSelected" @close="rescheduleClose" />
        </el-dialog>
      </div>
      <!-- 批量派工/改派 -->
      <div class="cartographer_big" v-if="!(!!~['detail'].indexOf(pageType) && pageCode != '')">
        <el-dialog
          title="批量派单"
          width="100%"
          :modal="false"
          :visible.sync="reassignmentBool"
          :before-close="reassignmentClose"
        >
          <Reassignment v-if="reassignmentBool" :recordSelected="recordSelected" @close="reassignmentClose" />
        </el-dialog>
      </div>
      <div class="tubiao">
        <span style="margin-right: 4px; font-weight: bold; font-size: 12px">工单标识说明：</span>
        <img :src="v4" style="width: 20px; height: 20px; margin: 0 3px" />
        <span style="margin-right: 4px; font-size: 12px; display: inline-block; width: 76px">【4.0工单】</span>
        <img :src="gc" style="width: 20px; height: 20px; margin: 0 3px" />
        <span style="margin-right: 4px; font-size: 12px; display: inline-block; width: 76px">【工程】</span>
        <img :src="jj" style="width: 20px; height: 20px; margin: 0 3px" />
        <span style="margin-right: 4px; font-size: 12px; display: inline-block; width: 76px">【加急】</span>
        <img :src="ls" style="width: 20px; height: 20px; margin: 0 3px" />
        <span style="margin-right: 4px; font-size: 12px; display: inline-block; width: 76px">【零售】</span>
        <img :src="yjs" style="width: 20px; height: 20px; margin: 0 3px" />
        <span style="margin-right: 4px; font-size: 12px; display: inline-block; width: 76px">【已结算】</span>
      </div>
      <div class="tubiao2">
        <span style="margin-right: 4px; font-weight: bold; font-size: 12px; opacity: 0">工单标识说明：</span>
        <img :src="ywg" style="width: 20px; height: 20px; margin: 0 3px" />
        <span style="margin-right: 4px; font-size: 12px; display: inline-block; width: 76px">【已完工】</span>
        <img :src="yc" style="width: 20px; height: 20px; margin: 0 3px" />
        <span style="margin-right: 4px; font-size: 12px; display: inline-block; width: 76px">【异常】</span>
        <img :src="zj" style="width: 20px; height: 20px; margin: 0 3px" />
        <span style="margin-right: 4px; font-size: 12px; display: inline-block; width: 76px">【自建工单】</span>
        <img :src="pjsq" style="width: 20px; height: 20px; margin: 0 3px" />
        <span style="margin-right: 4px; font-size: 12px; display: inline-block; width: 76px">【配件申请】</span>
        <img :src="pjdh" style="width: 20px; height: 20px; margin: 0 3px" />
        <span style="margin-right: 4px; font-size: 12px; display: inline-block; width: 76px">【配件到货】</span>
        <img :src="pjqx" style="width: 20px; height: 20px; margin: 0 3px" />
        <span style="margin-right: 4px; font-size: 12px; display: inline-block; width: 76px">【配件取消】</span>
      </div>
    </template-page>
    <!-- 工单详情 -->
    <div class="cartographer_big haidhead__" v-if="!!~['detail'].indexOf(pageType) && pageCode != ''">
      <el-dialog
        class="noinonnlinin"
        :title="'工单详情-' + id"
        width="100%"
        :modal="false"
        :visible.sync="detailFormBool"
        :before-close="handleClose"
      >
        <Detail v-if="detailFormBool" :id="id" :workOrderType="workOrderType" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { EventBus } from '@/utils/eventBus'
import TemplatePage from '@/components/template/template-page-1.vue'
import import_mixin from '@/components/template/import_mixin.js'
import operation_mixin from '@/components/template/operation_mixin.js'
import { listPageV2 } from '@/api/workOrder/orderType'
import {
  orderBaseList,
  orderBaseListExport,
  orderBaseStatusCount,
  orderBaseImport,
  orderBaseImport2,
  orderBaseImport3,
  orderBaseDetail
} from '@/api/workOrderPool.js'
import workOrderInfo from './detailModule/workOrderInfo/index.vue'
import Detail from './detail'
import Reassignment from './components/reassignment/index.vue'
import Reschedule from './components/reschedule/index.vue'
import { commonTemplateDownload } from '@/api/common.js'
import orderListColumn from '@/mixin/orderListColumn'
// -----------------------
import v4 from '@/assets/order/4.0@2x.png'
import gc from '@/assets/order/工程@2x.png'
import jj from '@/assets/order/加急@2x.png'
import ls from '@/assets/order/零售@2x.png'
import yjs from '@/assets/order/已结算@2x.png'
import ywg from '@/assets/order/已完工待结算@2x@2x.png'
import yc from '@/assets/order/异常@2x.png'
import zj from '@/assets/order/自建@2x.png'
import pjsq from '@/assets/order/配件申请中@2x.png'
import pjdh from '@/assets/order/配件已到货@2x.png'
import pjqx from '@/assets/order/配件已取消@2x.png'
export default {
  components: {
    TemplatePage,
    workOrderInfo,
    Detail,
    Reassignment,
    Reschedule
  },
  mixins: [import_mixin, operation_mixin, orderListColumn],
  data() {
    return {
      v4,
      gc,
      jj,
      ls,
      yjs,
      ywg,
      yc,
      zj,
      pjsq,
      pjdh,
      pjqx,
      id: this.$route.query.id || '',
      // 创建表单
      createFormBool: false,
      // 详情
      detailFormBool: true,
      // 批量改约
      rescheduleBool: false,
      // 批量派工/改派
      reassignmentBool: false,
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: true,
        selectable: this.selectable
      },
      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      recordSelected: [],
      orderTypeList: [],
      orderStatusList: [],
      defaultSearchData: [],
      workOrderType: 1,
      cloneWorkOrder: null,
      value1: new Date(),
      showTableBool: true
    }
  },
  watch: {
    value1() {
      this.showTableBool = false
      this.$nextTick(() => {
        this.showTableBool = true
      })
    }
  },
  computed: {
    moreParameters() {
      return [
        {
          name: '工单类型',
          key: 'orderSmallTypeText',
          value: '',
          conditions: [
            {
              label: '全部',
              value: ''
            },
            ...this.orderTypeList
          ]
        },
        {
          name: '工单状态',
          key: 'orderStatus',
          value: this.pageType == 'orderStatus' && this.pageCode ? this.pageCode : '',
          conditions: [
            {
              label: '全部',
              value: ''
            },
            ...this.orderStatusList
          ]
        }
      ]
    },
    // 用户信息
    userInfo() {
      return JSON.parse(localStorage.getItem('greemall_user'))
    },
    // 事件组合
    optionsEvensGroup() {
      return [
        [
          [
            this.optionsEvensAuth(['createWorkOrder', 'createWbWorkOrder'], {
              name: '创建工单',
              click: () => {}
            }),
            this.optionsEvensAuth('createWorkOrder', {
              click: () => {
                this.workOrderType = 1
                this.createFormBool = true
              }
            }),
            this.optionsEvensAuth('createGCWorkOrder', {
              click: () => {
                this.workOrderType = 2
                this.createFormBool = true
              }
            }),
            this.optionsEvensAuth('createWbWorkOrder', {
              click: () => {
                this.workOrderType = 4
                this.createFormBool = true
              }
            })
          ],
          [
            this.optionsEvensAuth(
              ['import4', 'importTemplate', 'downloadImportTemplate', 'importTemplate2', 'downloadImportTemplate2'],
              {
                name: '导入工单',
                click: () => {}
              }
            ),
            this.optionsEvensAuth('import4', ({ moduleName }) => {
              return {
                name: moduleName,
                render: () => {
                  return this.importButton(orderBaseImport3, moduleName)
                }
              }
            }),
            this.optionsEvensAuth('importTemplate', ({ moduleName }) => {
              return {
                name: moduleName,
                render: () => {
                  return this.importButton(orderBaseImport, moduleName)
                }
              }
            }),
            this.optionsEvensAuth('downloadImportTemplate', {
              click: () => {
                commonTemplateDownload({ name: '工单导入模板.xlsx' }, `${this.$route.meta.title}`)
                  .then(res => {
                    this.$message({
                      message: '下载成功',
                      type: 'success'
                    })
                  })
                  .catch(err => {
                    this.$message.error('下载失败')
                  })
              }
            }),
            this.optionsEvensAuth('importTemplate2', ({ moduleName }) => {
              return {
                name: moduleName,
                render: () => {
                  return this.importButton(orderBaseImport2, moduleName)
                }
              }
            }),
            this.optionsEvensAuth('downloadImportTemplate2', {
              click: () => {
                commonTemplateDownload({ name: '工单导入模板2.xlsx' }, `${this.$route.meta.title}`)
                  .then(res => {
                    this.$message({
                      message: '下载成功',
                      type: 'success'
                    })
                  })
                  .catch(err => {
                    this.$message.error('下载失败')
                  })
              }
            })
          ],
          [
            this.optionsEvensAuth(['bulkOrder', 'lotOrder'], {
              name: '批量操作',
              click: () => {}
            }),
            this.optionsEvensAuth('bulkOrder', {
              click: () => {
                if (this.recordSelected.length === 0) {
                  this.$message.warning('请勾选工单')
                  return
                }
                this.reassignmentBool = true
              }
            }),
            this.optionsEvensAuth('lotOrder', {
              click: () => {
                if (this.recordSelected.length === 0) {
                  this.$message.warning('请勾选工单')
                  return
                }
                this.rescheduleBool = true
              }
            })
          ]
        ]
      ]
    }
  },
  created() {
    this.initFun()
    EventBus.$on('handleOrderClone', () => {
      if (!(!!~['detail'].indexOf(this.pageType) && this.pageCode != '')) {
        this.handleClose()
      }
    })
    EventBus.$on('cloneWorkOrder', data => {
      if (!(!!~['detail'].indexOf(this.pageType) && this.pageCode != '')) {
        this.handleClose(() => {
          this.cloneWorkOrder = data
          this.workOrderType = data.saleType
          this.createFormBool = false
          this.$nextTick(() => {
            this.createFormBool = true
          })
        })
      }
    })
    if (!(!!~['detail'].indexOf(this.pageType) && this.pageCode != '')) {
      // 获取工单类型
      listPageV2({ pageNum: 1, pageSize: -1, params: [{ param: 'a.status', compare: '=', value: 'true' }] }).then(
        res => {
          var obj = {}
          res.data.records.map(item => {
            if (!obj[item.orderSmallTypeText]) {
              obj[item.orderSmallTypeText] = {
                value: item.orderSmallTypeText,
                label: item.orderSmallTypeText
              }
            }
          })
          this.orderTypeList = Object.values(obj)
        }
      )
    }
  },
  methods: {
    initFun() {
      if (this.pageType == 'detail') {
        this.id = this.pageCode
        orderBaseDetail({
          orderBaseId: this.id
        }).then(res => {
          this.workOrderType = Number(res?.data?.saleType)
          this.$nextTick(() => {
            this.detailFormBool = true
          })
        })
      }
      if (this.pageType == 'saleOrderId') {
        this.defaultSearchData = [{ param: 'a.sale_order_id', compare: '=', value: this.pageCode, label: '销售订单号' }]
      }
      if (this.pageType == 'pgIncreItemId') {
        this.defaultSearchData = [
          { param: 'a.pg_incre_order_id', compare: '=', value: this.pageCode, label: '增置服务订单ID' }
        ]
      }
      if (this.pageType == 'rpProjectRepairId') {
        this.defaultSearchData = [
          { param: 'a.rp_project_repair_id', compare: '=', value: this.pageCode, label: '维保配置ID' }
        ]
      }
      if (this.pageType == 'projectNo') {
        this.defaultSearchData = [{ param: 'a.project_no', compare: '=', value: this.pageCode, label: '工程编号' }]
      }
    },

    selectable(row, index) {
      var orderStatus = Object.entries(row.selectMapData.orderStatus).find(([key, val]) => val == row.orderStatus)?.[0]
      return (
        !row.isThreeOrder &&
        !['YWG', 'GCSZX', 'WDWG', 'YWGO'].includes(orderStatus) &&
        !['YJS', 'LRCD'].includes(orderStatus) &&
        !['YQX', 'FWZT', 'YCGB', 'FWQX'].includes(orderStatus) &&
        !row.rpProjectRepairId
      )
    },

    screeningAnalysis(jname, val) {
      if (jname == 'orderFlags') {
        return (val || []).map(item => item.tagName).join(',')
      } else {
        return val
      }
    },

    filterMethod(value, row, column) {
      if (column['property'] == 'orderFlags') {
        return (row[column['property']] || []).map(item => item.tagName).join(',') === value
      }
      return row[column['property']] === value
    },

    // 获取统计
    getOrderBaseStatusCount(...p) {
      orderBaseStatusCount(...p).then(res => {
        this.orderStatusList = [
          {
            label: '待预约',
            value: 'DYY'
          },
          {
            label: '待抢单',
            value: 'DQD'
          },
          {
            label: '待商户派工',
            value: 'DSHPG'
          },
          {
            label: '待网点派工',
            value: 'DWDPG'
          },
          {
            label: '待接单',
            value: 'DJD'
          },
          {
            label: '服务中',
            value: 'FWZ'
          },
          {
            label: '异常单',
            value: 'YCD'
          },
          {
            label: '已完工',
            value: 'YWGO'
          },
          {
            label: '已结算',
            value: 'YJS'
          },
          {
            label: '已取消',
            value: 'YQX'
          },
          {
            label: '配件申请中',
            value: 'PJSQZ'
          },
          {
            label: '配件已到货',
            value: 'PJYDH'
          },
          {
            label: '配件已取消',
            value: 'PJYQX'
          }
        ].map(item => {
          var data = res.data.find(val => val.orderStatus == item.value)
          if (data) {
            if (item.value == 'YWGO') {
              var data_ = res.data.find(val => val.orderStatus == 'YWG')
              var data_2 = res.data.find(val => val.orderStatus == 'GCSZX')
              var data_3 = res.data.find(val => val.orderStatus == 'YJS')
              item.label = `${item.label}(${data.total + data_.total + data_2.total + data_3.total})`
            } else {
              item.label = `${item.label}(${data.total})`
            }
          }
          return item
        })
      })
    },

    // 列表请求函数
    getList(p, cb) {
      var pam = JSON.parse(JSON.stringify(p))
      try {
        if (pam.orderStatus) {
          if (pam.orderStatus === 'YWGO') {
            pam.params.push({ param: 'a.order_status', compare: '=', value: ['YWG', 'YWGO', 'YJS', 'GCSZX'] })
            pam.orderStatus = ''
          } else {
            pam.params.push({ param: 'a.order_status', compare: '=', value: pam.orderStatus })
          }
        }
        if (pam.orderSmallTypeText) {
          pam.params.push({ param: 'a.order_small_type_text', compare: '=', value: pam.orderSmallTypeText })
        }
        if (this.value1) {
          pam.params.push(
            { param: 'a.create_time', compare: '>=', value: `${new Date(this.value1).getFullYear()}-1-1 00:00:00` },
            { param: 'a.create_time', compare: '<=', value: `${new Date(this.value1).getFullYear()}-12-31 23:59:59` }
          )
        }
        cb && cb(pam)
        return orderBaseList(pam)
      } catch (err) {
      } finally {
        this.$nextTick(() => {
          this.getOrderBaseStatusCount({
            orderSmallTypeText: pam.orderSmallTypeText || '',
            ...(() => {
              if (this.value1) {
                return {
                  startTime: `${new Date(this.value1).getFullYear()}-1-1 00:00:00`,
                  endTime: `${new Date(this.value1).getFullYear()}-12-31 23:59:59`
                }
              }
              return {}
            })()
          })
        })
      }
    },

    // 列表导出函数
    exportList: orderBaseListExport,

    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },

    operation() {
      return this.operationBtn({
        edit: {
          click: ({ row, index, column }) => {
            this.$router.push({
              name: 'workOrderPool',
              params: {
                pageName: row.id,
                pageType: 'detail',
                pageCode: row.id
              }
            })
          }
        }
      })
    },

    handleClose(cb) {
      this.$router.push({
        name: 'workOrderPool',
        params: {},
        query: {}
      })
      this.$nextTick(() => {
        this.cloneWorkOrder = null
        this.createFormBool = false
        this.detailFormBool = false
        this.recordSelected = []
        this.$refs?.pageRef?.refreshList()
        if (cb && typeof cb === 'function') {
          cb()
        }
      })
    },

    rescheduleClose() {
      this.rescheduleBool = false
      this.recordSelected = []
      this.$refs?.pageRef?.refreshList()
    },

    reassignmentClose() {
      this.reassignmentBool = false
      this.recordSelected = []
      this.$refs?.pageRef?.refreshList()
    }
  }
}
</script>

<style lang="scss" scoped>
.haidhead__ {
  ::v-deep .noinonnlinin {
    & > div > .el-dialog__header {
      display: none !important;
    }
    & > div > .el-dialog__body {
      width: 100%;
      height: 100% !important;
      position: relative;
      box-sizing: border-box;
      padding: 0px;
      overflow-y: auto;
    }
  }
}
.tubiao {
  position: absolute;
  bottom: 35px;
  left: 20px;
  z-index: 10;
  width: 60%;
  height: auto;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  z-index: -1;
}
.tubiao2 {
  position: absolute;
  bottom: 5px;
  left: 20px;
  z-index: 10;
  width: 60%;
  height: auto;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  z-index: -1;
}
</style>
