<template>
  <!-- 工单池 -->
  <template-page 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 class="cartographer_big">
      <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">
      <el-dialog :title="'工单详情-' + id" width="100%" :modal="false" :visible.sync="detailFormBool"
        :before-close="handleClose">
        <Detail v-if="detailFormBool" :id="id" :workOrderType="workOrderType" />
      </el-dialog>
    </div>
    <!-- 批量预约/改约 -->
    <div class="cartographer_big">
      <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">
      <el-dialog title="批量派单" width="100%" :modal="false" :visible.sync="reassignmentBool"
        :before-close="reassignmentClose">
        <Reassignment v-if="reassignmentBool" :recordSelected="recordSelected" @close="reassignmentClose" />
      </el-dialog>
    </div>
  </template-page>
</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, 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"
export default {
  components: {
    TemplatePage,
    workOrderInfo,
    Detail,
    Reassignment,
    Reschedule
  },
  mixins: [import_mixin, operation_mixin, orderListColumn],
  data() {
    return {
      id: this.$route.query.id || '',
      // 创建表单
      createFormBool: false,
      // 详情
      detailFormBool: false,
      // 批量改约
      rescheduleBool: false,
      // 批量派工/改派
      reassignmentBool: false,
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: true,
        selectable: this.selectable
      },
      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      recordSelected: [],
      orderTypeList: [],
      orderStatusList: [],
      defaultSearchData: [],
      workOrderType: 1,
      cloneWorkOrder: null
    }
  },
  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(["importTemplate", "downloadImportTemplate", 'importTemplate2', 'downloadImportTemplate2'], {
              name: '导入工单',
              click: () => { }
            }),
            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', () => {
      this.handleClose()
    })
    EventBus.$on('cloneWorkOrder', (data) => {
      this.handleClose(() => {
        this.cloneWorkOrder = data
        this.workOrderType = data.saleType
        this.createFormBool = false
        this.$nextTick(() => {
          this.createFormBool = true
        })
      })
    })
    // 获取工单类型
    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) {
      return !["YWG", "YJS", "YQX"].includes(Object.entries(row.selectMapData.orderStatus).find(([key, val]) => val == row.orderStatus)?.[0]) && !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: "YWG"
        }, {
          label: "已结算",
          value: "YJS"
        }, {
          label: "已取消",
          value: "YQX"
        }].map(item => {
          var data = res.data.find(val => val.orderStatus == item.value)
          if (data) {
            item.label = `${item.label}(${data.total})`
          }
          return item
        })
      })
    },

    // 列表请求函数
    getList(p, cb) {
      var pam = JSON.parse(JSON.stringify(p))
      try {
        if (pam.orderStatus) {
          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 })
        }
        cb && cb(pam)
        return orderBaseList(pam)
      } catch (err) {
      } finally {
        this.$nextTick(() => {
          this.getOrderBaseStatusCount({ orderSmallTypeText: pam.orderSmallTypeText || "" })
        })
      }
    },

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

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

    operation() {
      return this.operationBtn({
        edit: {
          click: ({ row, index, column }) => {
            this.id = row.id
            this.workOrderType = Number(Object.entries(row?.selectMapData?.saleType || {}).find(([key, val]) => val == row.saleType)?.[0] || 1)
            this.$nextTick(() => {
              this.detailFormBool = true
            })
          }
        }
      })
    },

    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></style>
