<template>
  <!-- 订单管理 -->
  <div>
    <actionBar menuTitle="订单管理" :formList="formList" :ruleForm="searchRuleForm" @searchProtocol="searchProtocol">
    </actionBar>
    <tables :key="Math.random()" :suspension="true" :tableList="tableList" :tableData="tableData"
      @buttonData="buttonData"></tables>
    <!-- 分页 -->
    <div class="paging_bottom" v-if="Total">
      <pagination :total="Total" :currentPage="Pagination.PageIndex" @changeSize="changeSize"
        @changeCurrent="changeCurrent">
      </pagination>
    </div>
    <el-dialog :title="staffTitle" :visible.sync="staffDialogVisible" width="60%" :close-on-click-modal="false">
      <forms ref="childRules" :formNewList="formRuleList" :ruleForm="ruleForm" labelWidth="100px"></forms>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getOrder,
    getCustomer,
    addCustomer,
    addOrder,
    getDelivery,
    getSysuser,
    cancelOrder,
    orderDelivery
  } from '@/api/order'
  import {
    getGoods,
  } from '@/api/commodity'
  import actionBar from '@/components/actionBar'
  import tables from '@/components/tables'
  import pagination from '@/components/pagination'
  import forms from '@/components/forms'
  import {
    formRules,
    employee
  } from "./order.js";
  import {
    urbanArea
  } from '@/assets/js/districtCode'
  import {
    orderStatus
  } from '@/assets/js/blockSort'
  export default {
    components: {
      actionBar,
      tables,
      pagination,
      forms
    },
    data() {
      return {
        staffTitle: '添加',
        staffDialogVisible: false,
        formList: [{
          type: 'picker',
          label: '订单时间',
          field: 'time',
          placeholder: '订单时间',
        }, {
          type: 'select',
          label: '订单状态',
          field: 'state',
          placeholder: '订单状态',
          options: orderStatus(),
        }, {
          type: 'input',
          label: '客户电话',
          field: 'phone',
          placeholder: '客户电话',
        }],
        searchRuleForm: {
          time: [],
          state: '',
          phone: '',
        },
        tableList: employee(),
        tableData: [],
        Pagination: {
          PageIndex: 1,
          PageSize: 10,
        },
        Total: 0,
        ruleForm: {},
        formRuleList: [],
        searchValue: {},
        orderId: '',
        operationType: '',
      }
    },
    mounted() {
      const dataList = formRules();
      this.formRuleList = dataList;
      this.getList()
    },
    methods: {
      // 搜索
      searchProtocol(value) {
        this.searchValue = value
        if (value.time) {
          this.searchValue.orderStartTime = value.time[0]
          this.searchValue.orderEndTime = value.time[1]
          delete this.searchValue.time
        }
        this.getList()
      },
      // 获取订单列表
      getList() {
        var params = {
          page: this.Pagination.PageIndex,
          pageSize: this.Pagination.PageSize,
          ...this.searchValue
        }
        getOrder(params).then(res => {
          // console.log(res,32)
          if (res.code == 200) {
            this.tableData = res.data.list
            this.Total = res.data.count
            this.getDistributionStore()
          }
        })
      },
      // 获取配送门店
      getDistributionStore() {
        getDelivery().then(res => {
          // console.log(res, '门店')
          if (res.code == 200) {
            const arr = res.data
            const childrenNav = flat(arr)
            const arrList = []
            childrenNav.forEach((item, index) => {
              const commodity = {
                label: item.name,
                value: item.id,
              }
              arrList.push(commodity)
            })
            this.optionMatching(arrList, 'storeId')

            function flat(arr) {
              return [].concat(...arr.map(item => [].concat(item, ...flat(item.children))));
            }
          }
        })
      },
      buttonData(row, type) {
        this.operationType = type
        this.getAcquireGoods(row.goodsId)
        this.$set(this.ruleForm, 'name', row.customer.name)
        this.$set(this.ruleForm, 'phone', row.customer.principalPhone)
        var arr1 = ''
        var cityArr = urbanArea()
        var city = this.cityScreening(row.customer.city, cityArr)
        var area = this.cityScreening(row.customer.area, cityArr)
        arr1 = city + area
        this.$set(this.ruleForm, 'cityRegion', arr1)
        this.$set(this.ruleForm, 'address', row.customer.address)
        this.$set(this.ruleForm, 'quantity', row.quantity)
        this.$set(this.ruleForm, 'remark', row.customer.remark)
        this.$set(this.ruleForm, 'state', row.state)
        if (row.storeId != 0) {
          this.$set(this.ruleForm, 'storeId', String(row.storeId))
          this.getCourier(row.storeId)
          this.$set(this.ruleForm, 'userId', String(row.userId))
        }
        if (type == 'edit') {
          this.staffTitle = '编辑'
        } else {
          this.staffTitle = '详情'
        }
        this.staffDialogVisible = true
      },
      // 获取商品
      getAcquireGoods(goodsId) {
        getGoods().then(res => {
          if (res.code == 200) {
            const arr = res.data.list
            arr.forEach((item, index) => {
              if (item.id == goodsId) {
                this.$set(this.ruleForm, 'goodsId', item.name)
              }
            })
          }
        })
      },
      // 获取配送员
      getCourier(id) {
        getSysuser({
          storeId: id,
        }).then(res => {
          // console.log(res, '配送员')
          if (res.code == 200) {
            const arrList = []
            const arr = res.data.list
            arr.forEach((item, index) => {
              const commodity = {
                label: item.nickName,
                value: item.id,
              }
              arrList.push(commodity)
            })
            this.optionMatching(arrList, 'userId')
          }
        })
      },
      // 城市筛选
      cityScreening(value, list) {
        function getChildById(parentArray, id) {
          for (let i = 0; i < parentArray.length; i++) {
            if (parentArray[i].value === id) { // 如果当前元素的ID与目标ID相等，则返回该元素
              return parentArray[i];
            } else if (parentArray[i].children && Array.isArray(parentArray[i].children)) { // 判断当前元素是否有子节点且类型为数组
              const result = getChildById(parentArray[i].children, id); // 对子节点进行递归调用
              if (result !== null) { // 若子节点存在结果，则返回该结果
                return result;
              }
            }
          }
          return null; // 没有找到符合条件的元素时返回null
        }
        var name = getChildById(list, value)
        if (name != null) {
          return name.label
        }
      },
      // 选项赋值
      optionMatching(value, field) {
        this.formRuleList.forEach((item, index) => {
          if (item.field == field) {
            item.options = value
          }
        })
      },
      changeSize(val) {
        this.Pagination.PageSize = val
        this.getList()
      },
      changeCurrent(val) {
        this.Pagination.PageIndex = val
        this.getList()
      },
    }
  }
</script>

<style lang="scss" scoped>
</style>
