<template>
  <!-- 坐席下单 -->
  <div>
    <actionBar menuTitle="坐席下单" :operateList="operateList" :formList="formList" :ruleForm="searchRuleForm"
      @openModel="openModel" @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="70%" :close-on-click-modal="false"
      @close="closeDialog">
      <div class="card_podia">
        <div :style="{width:operationType == 'edit' ? '100%' : '70%'}">
          <forms ref="childRules" labelPosition="left" :formNewList="formRuleList" :ruleForm="ruleForm"
            labelWidth="120px" @numberSearch="numberSearch" @changeSelect="changeSelect"></forms>
        </div>
        <div class="seating_order" v-if="operationType != 'edit'">
          <div class="card_seating_order">
            <span>订单记录</span>
            <el-divider></el-divider>
            <div style="display: flex;flex-direction: column;" v-if="orderRecordList.length > 0">
              <div v-for="(item,index) in orderRecordList" :key="index">
                {{item.orderTime}} {{item.goods.name}}{{item.spec.name}} {{item.quantity}}瓶
              </div>
            </div>
            <div v-else class="center_in" style="color: #909399;">暂无数据</div>
            <div style="margin-top: 50px;">客户用瓶信息</div>
            <el-divider></el-divider>
            <div style="display: flex;flex-direction: column;" v-if="informationList.length > 0">
              <div v-for="(item,index) in informationList" :key="index">
                {{item.borrowTime}} {{item.innerCode}}
              </div>
            </div>
            <div class="center_in" style="color: #909399;" v-else>暂无数据</div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer" v-if="operationType != 'logs'">
        <el-button plain @click="staffDialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="confirmLoading" @click="handleAdd">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getOrder,
    getCustomer,
    addCustomer,
    addOrder,
    putOrder,
    getDelivery,
    getSysuser,
    cancelOrder,
    getBorrowGasCylinder
  } from '@/api/order'
  import {
    putCustomer,
  } from '@/api/record'
  import {
    getGoods,
  } from '@/api/commodity'
  import {
    getCylinder,
  } from '@/api/specification'
  import actionBar from '@/components/actionBar'
  import tables from '@/components/tables'
  import pagination from '@/components/pagination'
  import forms from '@/components/forms'
  import {
    urbanArea
  } from '@/assets/js/districtCode'
  import {
    orderStatus
  } from '@/assets/js/blockSort'
  import {
    formRules,
    employee
  } from "./orderTable.js";
  import axios from 'axios'
  export default {
    components: {
      actionBar,
      tables,
      pagination,
      forms
    },
    data() {
      return {
        operateList: [{
          type: 'add',
          title: '添加客户订单',
          icon: 'el-icon-plus',
        }],
        staffTitle: '添加',
        staffDialogVisible: false,
        Pagination: {
          PageIndex: 1,
          PageSize: 10,
        },
        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: [],
        Total: 0,
        formRuleList: [],
        orderRecordList: [],
        informationList: [],
        ruleForm: {},
        operationType: '',
        confirmLoading: false,
        detailedAddress: '',
        searchValue: {},
        clientId: '',
        orderId: '',
      }
    },
    mounted() {
      let flag = this.$route.query.flag
      if (flag) {
        this.staffDialogVisible = true
        this.ruleForm.phone = this.$route.query.phone
        this.numberSearch(this.ruleForm.phone)
      }
      const dataList = formRules();
      this.formRuleList = dataList;
      this.getDistributionStore()
      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 = {
          source: 1,
          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
          }
        })
      },
      // 手机号搜索
      numberSearch(phone) {
        getCustomer({
          phone: phone,
        }).then(res => {
          if (res.code == 200) {
            const arr = res.data
            // this.ruleForm.type = arr.type
            this.$set(this.ruleForm, 'type', arr.type)
            if (arr.type == 0) {
              // this.ruleForm.name = arr.shopName
              this.$set(this.ruleForm, 'name', arr.shopName)
            } else {
              // this.ruleForm.name = arr.principalName
              this.$set(this.ruleForm, 'name', arr.principalName)
            }
            // this.ruleForm.address = arr.address
            this.$set(this.ruleForm, 'address', arr.address)
            // this.ruleForm.remark = arr.remark
            this.$set(this.ruleForm, 'remark', arr.remark)
            var arr1 = []
            arr1.push(arr.city)
            arr1.push(arr.area)
            this.$set(this.ruleForm, 'cityRegion', arr1)
            // this.ruleForm.cityRegion = arr1
            this.ruleForm.lng = arr.lng
            this.ruleForm.lat = arr.lat
            this.$refs.childRules.curLoading = false
            this.getOrderInformation(arr.id)
          } else {
            this.$refs.childRules.curLoading = false
          }
        })
      },
      // 下单
      async handleAdd() {
        let flag = this.$refs['childRules'].validateForm();
        if (flag) {
          var params = {
            name: this.ruleForm.name,
            principalPhone: this.ruleForm.phone,
            address: this.ruleForm.address,
            remark: this.ruleForm.remark,
            type: this.ruleForm.type,
            city: this.ruleForm.cityRegion[0],
            area: this.ruleForm.cityRegion[1]
          }
          let arr = await this.longitudeLatitude(params)
          var propertyName = arr.location.split(",")
          params.lng = Number(propertyName[0])
          params.lat = Number(propertyName[1])
          if (this.operationType == 'edit') {
            await putCustomer({
              id: this.clientId,
              ...params
            }).then(res => {
              if (res.code == 200) {
                this.placePutOrder(params)
              }
            })
          } else {
            await addCustomer(params).then(res => {
              if (res.code == 200) {
                this.placeOrder(res.data)
              }
            })
          }
        } else {
          this.$message.error('表单信息不完整，请继续填写完整');
        }
      },
      // 下单
      async placeOrder(customerId) {
        var params = {
          customerId: customerId,
          phone: this.ruleForm.phone,
          address: '',
          source: 1,
          storeId: Number(this.ruleForm.storeId),
          goodsId: Number(this.ruleForm.goodsId),
          quantity: Number(this.ruleForm.quantity),
          specId: Number(this.ruleForm.specId),
          userId: Number(this.ruleForm.userId),
          remark: this.ruleForm.orderNote,
        }
        var cityArr = urbanArea()
        var city = this.cityScreening(this.ruleForm.cityRegion[0], cityArr)
        var area = this.cityScreening(this.ruleForm.cityRegion[1], cityArr)
        this.detailedAddress = city + area + this.ruleForm.address
        if (this.detailedAddress) {
          params.address = this.detailedAddress
        } else {
          params.address = this.ruleForm.address
        }
        addOrder(params).then(res => {
          if (res.code == 200) {
            this.staffDialogVisible = false
            this.$message({
              message: '操作成功',
              type: 'success'
            });
            this.getList()
          }
        })
      },
      // 修改订单
      placePutOrder(value) {
        var params = {
          id: this.orderId,
          phone: this.ruleForm.phone,
          address: '',
          storeId: Number(this.ruleForm.storeId),
          goodsId: Number(this.ruleForm.goodsId),
          quantity: Number(this.ruleForm.quantity),
          specId: Number(this.ruleForm.specId),
          userId: Number(this.ruleForm.userId),
          remark: this.ruleForm.orderNote,
        }
        var cityArr = urbanArea()
        var city = this.cityScreening(this.ruleForm.cityRegion[0], cityArr)
        var area = this.cityScreening(this.ruleForm.cityRegion[1], cityArr)
        this.detailedAddress = city + area + this.ruleForm.address
        if (this.detailedAddress) {
          params.address = this.detailedAddress
        } else {
          params.address = this.ruleForm.address
        }
        putOrder(params).then(res => {
          // console.log(res, 77)
          if (res.code == 200) {
            this.staffDialogVisible = false
            this.$message({
              message: res.msg,
              type: 'success'
            });
            this.getList()
          }
        })
      },
      // 获取经纬度
      longitudeLatitude(value) {
        var cityArr = urbanArea()
        var city = this.cityScreening(value.city, cityArr)
        var area = this.cityScreening(value.area, cityArr)
        return new Promise((resolve, inject) => {
          axios.get('https://restapi.amap.com/v3/geocode/geo', {
            params: {
              key: 'fcddcc366fd5bd355e35f01b7cce82ef',
              address: city + area + value.address,
            }
          }).then((res) => {
            resolve(res.data.geocodes[0])
          }).catch(() => {
            this.confirmLoading = false
          })
        })
      },
      // 城市筛选
      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
        }
      },
      // 获取配送门店
      getDistributionStore() {
        getDelivery().then(res => {
          // console.log(res, '门店')
          if (res.code == 200) {
            this.getAcquireGoods()
            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))));
            }
          }
        })
      },
      // 门店选择
      changeSelect(row, field) {
        if (field == 'storeId') {
          this.getCourier(row)
        }
      },
      // 获取配送员
      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')
          }
        })
      },
      // 获取商品
      getAcquireGoods() {
        getGoods().then(res => {
          if (res.code == 200) {
            const arrList = []
            const arr = res.data.list
            arr.forEach((item, index) => {
              const commodity = {
                label: item.name,
                value: item.id,
              }
              arrList.push(commodity)
            })
            this.optionMatching(arrList, 'goodsId')
            this.getSpecification()
          }
        })
      },
      // 获取规格
      getSpecification() {
        getCylinder().then(res => {
          const arrList = []
          const arr = res.data.list
          arr.forEach((item, index) => {
            const commodity = {
              label: item.name,
              value: item.id,
            }
            arrList.push(commodity)
          })
          this.optionMatching(arrList, 'specId')
        })
      },
      // 选项赋值
      optionMatching(value, field) {
        this.formRuleList.forEach((item, index) => {
          if (item.field == field) {
            item.options = value
          }
        })
      },
      // 获取客户订单信息
      getOrderInformation(id) {
        getOrder({
          customerId: id,
        }).then(res => {
          if (res.code == 200) {
            this.orderRecordList = res.data.list
            this.getGasCylinder(id)
          }
        })
      },
      // 获取客户订单信息
      getGasCylinder(id) {
        getBorrowGasCylinder({
          customerId: id,
        }).then(res => {
          if (res.code == 200) {
            this.informationList = res.data.list
          }
        })
      },
      openModel(type) {
        this.operationType = type
        if (type == 'add') {
          this.staffTitle = '添加订单'
        }
        this.staffDialogVisible = true
      },
      buttonData(row, type) {
        // console.log(row, type, 25)
        if (type == 'logs') {
          this.formRuleList.forEach((item, index) => {
            item.disabled = true
          })
        }
        this.orderId = row.id
        this.operationType = type
        if (type == 'logs' || type == 'edit') {
          this.getCourier(row.storeId)
          this.ruleForm.phone = row.customer.principalPhone
          this.$set(this.ruleForm, 'type', row.customer.type)
          this.$set(this.ruleForm, 'name', row.customer.name)
          this.$set(this.ruleForm, 'address', row.customer.address)
          var arr1 = []
          arr1.push(row.customer.city)
          arr1.push(row.customer.area)
          this.$set(this.ruleForm, 'cityRegion', arr1)
          this.$set(this.ruleForm, 'remark', row.customer.remark)
          this.$set(this.ruleForm, 'orderNote', row.remark)
          if (row.storeId != 0) {
            this.$set(this.ruleForm, 'storeId', String(row.storeId))
          }
          if (row.userId != 0) {
            this.$set(this.ruleForm, 'userId', String(row.userId))
          }
          this.$set(this.ruleForm, 'goodsId', String(row.goodsId))
          this.$set(this.ruleForm, 'specId', String(row.specId))
          this.$set(this.ruleForm, 'quantity', row.quantity)
          this.getOrderInformation(row.customer.id)
          this.clientId = row.customer.id
          this.$forceUpdate()
          this.staffTitle = '座席下单'
          this.staffDialogVisible = true
        } else if (type == 'del') {
          this.getCancelOrder(row.id)
        }
      },
      // 取消订单
      getCancelOrder(ID) {
        this.$confirm('此操作将永久取消该订单, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          cancelOrder({
            id: ID,
          }).then((res) => {
            if (res.code == 200) {
              this.$message({
                message: '操作成功',
                type: 'success'
              });
              this.getList()
            }
          })
        }).catch(() => {
          // console.log('取消')
        });
      },
      changeSize(val) {
        this.Pagination.PageSize = val
        this.getList()
      },
      changeCurrent(val) {
        this.Pagination.PageIndex = val
        this.getList()
      },
      closeDialog() {
        this.orderRecordList = []
        this.informationList = []
        this.ruleForm = {}
        this.formRuleList.forEach((item, index) => {
          item.disabled = false
        })
        this.$refs.childRules.resetCheck();
      }
    }
  }
</script>

<style lang="scss" scoped>
  ::v-deep .el-dialog {
    margin-top: 8vh !important;
  }

  .card_podia {
    display: flex;
  }

  .seating_form_card {
    width: 70%;
  }

  .seating_order {
    width: 30%;
  }

  .card_seating_order {
    margin: 0px 20px;
  }
</style>
