<template>
  <div>
    <crud-template v-if="itemStart" class="as-weight" :ref="(el) => (crudRef = el)" :home-data="field"
      @btnSearch="btnSearch" @selectionChangeHandle="selectionChangeHandle" @refreshLeft="refreshLeft"
      :tableData="tableData" @CurrentChange="handleCurrentChange" @cancel="cancel" @handleInfo="handleInfo"
      @pageSizeChange="(val) => {
      field.paging.currentPage = 1
      field.paging.pageSize = val
      getList()
    }">
      <template #search>
        <el-input maxlength="60" v-trim clearable v-model="searchForm.orderNo" style="width: 200px"
          placeholder="请输入单号" />
        <el-input maxlength="60" v-trim clearable v-model="searchForm.customerIdNum" style="width: 200px"
          placeholder="请输入证件号" />
        <el-input maxlength="60" v-trim clearable v-model="searchForm.customerTel" style="width: 200px"
          placeholder="请输入用户手机号" />
        <el-input maxlength="60" v-trim clearable v-model="searchForm.productName" style="width: 200px"
          placeholder="请输入产品名称" />
        <el-input maxlength="60" v-trim clearable v-model="searchForm.vehiclePlate" placeholder="请输入车牌号"
          :style="{ width: '320px', margin: '0 10px 10px 0' }">
          <template #append>
            <el-select clearable v-model="searchForm.vehiclePlateColor" placeholder="请选择车牌颜色"
              style="width: 150px; height: 32px">
              <el-option :label="item.label" :key="item.label" :value="item.value" v-for="item in VEHICLE_COLOR_TYPE" />
            </el-select>
          </template>
        </el-input>
        <!-- <el-select clearable v-model="searchForm.artificialStatus" style="width: 200px" placeholder="请选择审核类型">
          <el-option v-for="item in artificialStatusList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select> -->
        <el-select clearable v-model="searchForm.vanType" style="width: 200px" placeholder="请选择车辆类型">
          <el-option v-for="item in vehicleTypes" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-select clearable v-model="searchForm.promotionModes" style="width: 200px" placeholder="请选择办理方式">
          <el-option v-for="item in PATTERN_TYPE" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <!-- <el-select clearable v-model="searchForm.orderType" style="width: 200px" placeholder="请选择订单类型">
          <el-option v-for="item in ORDER_TYPE" :key="item.value" :label="item.label" :value="item.value" />
        </el-select> -->
        <!-- <div class="date-label">创建时间:</div> -->
        <el-date-picker unlink-panels v-model="searchForm.time" type="datetimerange" range-separator="到"
          start-placeholder="订单创建开始日期" end-placeholder="订单创建结束日期" format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss" />
      </template>
      <!-- <template #CustomButton>
        <el-button v-if="IsPermission(route, 'GET_ORDER_LIST')" type="primary" @click="getOrderFn(1)">
          <span style="font-family: '微软雅黑', 'KaiTi', serif;">批量领取订单</span>
        </el-button>
      </template> -->
      <template #tableOperation>
        <el-tabs @tab-click="handleClick" v-model="activeName">
          <el-tab-pane v-for="(item, index) in tageList" :key="index" :label="item.label"
            :name="item.name"></el-tab-pane>
        </el-tabs>
      </template>
      <template #operation="{ scope }">
        <el-button style="margin: 10px 5px;" v-if="IsPermission(route, 'INFO_LIST')" type="warning" size="small"
          @click="audit(scope.$index, scope.row, false)">
          详情
        </el-button>
        <el-button style="margin: 10px 5px;"
          v-if="pass=='2'&&IsPermission(route, 'AUDIT_LIST')"
          type="success" size="small" @click="audit(scope.$index, scope.row, true)">
          审核
        </el-button>
        <el-button :loading="scope.row.btnLoading"
          v-if="pass=='1' && IsPermission(route, 'GET_ORDER_LIST')"
          type="primary" size="small" @click="getOrderFn(2, scope.row)">
          <span style="font-family: '微软雅黑', 'KaiTi', serif;">领取订单</span>
        </el-button>
      </template>
    </crud-template>
    <el-dialog v-model="check" width="30%" title="审核">
      <el-form ref="form" :model="autdis"
        :rules="{ reason: [{ required: true, message: '驳回类型不能为空', trigger: 'change' }] }" label-width="80px">
        <el-form-item label="">
          <el-radio-group v-model="autdis.auditStatus">
            <el-radio label="true">审核通过</el-radio>
            <el-radio label="false">审核不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="autdis.auditStatus != 'true'" label="审核原因" prop="reason">
          <!-- <el-select clearable @change="autdisReasonChange" v-model="autdis.reason" placeholder="请选择审核原因类型">
            <el-option :label="item.label" :key="item.value" :value="item.value"
              v-for="item in NEW_CSMSN_APPLY_REASON" />
          </el-select> -->
          <el-input v-trim clearable type="textarea"  v-model="autdis.reason" :placeholder="`审核不通过原因`"
            maxlength="200" show-word-limit></el-input>
        </el-form-item>
        <el-form-item v-if="autdisReasonType == '8' && autdis.auditStatus != 'true'" label="其他原因" prop="reason1">
          <el-input v-trim clearable type="textarea"  v-model="autdis.reason1" :placeholder="`审核不通过原因`"
            maxlength="200" show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="check = false">取 消</el-button>
        <el-button type="primary" @click="checkForm(form)">确 定</el-button>
      </template>
    </el-dialog>
  </div>
  <!-- 详情弹窗 -->
  <el-dialog class="detail-dialog" :title="detailDialogTitle" v-model="visible">
    <div v-if="detailDialogTitle == '订单详情'">
      <el-affix style="position: absolute; top: 0; right: 80px" v-if="pass=='2'&& autdisButton"
        :offset="offset + 50">
        <el-button type="danger" size="small" @click="handleAudit">
          审核
        </el-button>
      </el-affix>
      <orderInfo :infoData="rowData"></orderInfo>
    </div>
  </el-dialog>
</template>

<!-- 订单审核 -->
<script lang="ts" setup>
  // @ts-ignore crudFrom模板
  import CrudTemplate from '@/crud/index.vue'
  import { ref, computed, onMounted, reactive, nextTick, ComputedRef } from 'vue'
  import $storeinitData from '@/store/initData' //引入tab vuex
  import { ElMessage, ElMessageBox } from 'element-plus'
  import BaseService from '@/utils/baseService'
  import { useRoute } from 'vue-router'
  import { IsPermission } from '@/router/routerUtil'
  import moment from 'moment'
  import { getCache } from '@/utils/cache'
  import { getAudit, getOrderInfo } from '@/api/onlineBusinessHall/orderManagement'
  // import orderInfo from './orderInfo.vue'
  import orderInfo from "@/components/orderInfo/index.vue";

  //或取路由传入过来的对象数据
  const route = useRoute()

  const crudRef = ref()
  const itemStart = ref(true)
  const searchForm = ref({
    artificialStatus: '',
    orderNo: '',
    productName: '',
    vehiclePlate: '',
    vanType: '',
    orderType: '',
    orderStep: '',
    time: '',
    vehiclePlateColor: '',
    promotionModes: '',
    customerIdNum: '',
    customerTel: ''
  })

  const overdueList = [
    {
      label: '逾期',
      value: '1',
    },
    {
      label: '未逾期',
      value: '0',
    },
  ]
  const artificialStatusList = [
    {
      label: '系统审核',
      value: 2
    },
    {
      label: '人工审核',
      value: 1
    },
  ]
  //订单阶段
  const ORDER_STAGE_TYPE = computed(() => {
    return $storeinitData.state.dictData['ISSUE_ORDER_STEP'] || []
  })

  //订单状态
  const ORDER_TYPE = computed(() => {
    return $storeinitData.state.dictData['ORDER_TYPE'] || []
  })
  //车牌颜色
  const VEHICLE_COLOR_TYPE = computed(() => {
    return $storeinitData.state.dictData['VEHICLE_COLOR_TYPE'] || []
  })

  // 车辆类型
  const vehicleTypes = computed(() => {
    return $storeinitData.state.dictData['VAN_TYPE'] || []
  })

  //办理模式
  const PATTERN_TYPE = computed(() => {
    return $storeinitData.state.dictData['PATTERN_TYPE'] || []
  })

  //订单状态
  const ORDER_STATUS = computed(() => {
    return $storeinitData.state.dictData['ISSUE_ORDER_STATUS'] || []
  })

  const ID_TYPE = computed(() => {
    return $storeinitData.state.dictData["ID_TYPE"] ?? [];
  }); //用户证件类型

  const NEW_CSMSN_APPLY_REASON = computed(() => {
    return $storeinitData.state.dictData['NEW_CSMSN_APPLY_REASON'] || []
  })


  const value1 = ref() // 筛选时间
  const tableData: any = ref([])
  const initItem = {
    id: '',
  }
  const addForm: any = ref(initItem)
  let formLabelWidth = '180px'
  //表单数据配置
  const field = ref({
    tabSize: 'small', //Table 的尺寸 large / default /small (默认default)
    searchShow: IsPermission(route, 'QUERY_BASE'), //是否显示搜索模块(默认false)
    border: true, //是否添加边框(默认false)
    dialogCustom: false, //自定义Dialog (默认false)
    dialogFooter: true, //隐藏弹窗页脚显示 (默认false)
    dialogWidth: '60%', //dialog宽度 (默认40%)
    crudShow: true, //是否显示CURD操作栏 (默认true)
    crudChildShow: true, //是否显示CURD子操作栏 (默认true)
    paginStart: true, //是否显示分页查询 (默认false)
    titleDialog: '', //table 标题
    tableOperation: true,
    isPageSizes: true,
    pageLayout: 'total, sizes, prev, pager, next',
    paging: {
      pageSize: 10,
      currentPage: 1,
      total: 0,
    },
    crud: {
      add: false,
      edit: false,
      delete: false,
      derive: false,
      search: false,
      refresh: false,
    },
    searchOperation: {
      isDownload: false,
      isAdd: false,
      isTransferMachine: false,
    },
    tableSize: -1,
    operateShow: true, //是否为表格添加操作栏(默认true)
    operateTitle: '操作', //操作栏标题(默认为"")
    operateFixed: true, //操作栏是否固定(默认false)
    operateWidth: '180', //操作栏宽度
    operate: {
      edit: false, //是否编辑(默认true)
      delete: false, //是否删除(默认true)
      announcement: false, // 公告
      info: false, // 详情
      remark: false, // 详情
    },
    extend: [
      {
        type: 'index',
        label: '序号',
      },
    ],
    field: [
      // {
      //   label: '',
      //   prop: '',
      //   hide: !IsPermission(route, 'GET_ORDER_LIST'),
      //   type: 'selection',
      // },
      {
        prop: 'orderNo',
        label: '单号',
      },
      {
        prop: 'productName',
        label: '产品名称',
      },
      {
        prop: 'productTypes',
        label: '产品类型',
        funRuleStarts: true,
        funRule: (value: any) => {
          return value == "1" ? "自营产品" : value == "0" ? "非自营产品" : "---";
        },      
      },
      {
        prop: 'promotionModes',
        label: '办理方式', 
        listData: PATTERN_TYPE
      },
      {
        prop: 'isValueCard',
        label: '卡类型',
        funRuleStarts: true,
        funRule: (money: any) => {
          //1-储值卡 2-记账卡
          return money == '1' ? '储值卡' : '记账卡'
        },
      },
      {
        prop: 'vehicleType',
        label: '车辆类型',
        // listData: vehicleTypes
      },
      {
        prop: 'userType',
        label: '用户类型', //PERSONAL_USER - 个人用户 UNIT_USER - 单位用户
        funRuleStarts: true,
        funRule: (money: any) => {
          return money === 'PERSONAL_USER' ? '个人用户' : '单位用户'
        },
      },
      {
        prop: 'customerTel',
        label: '手机号',
      },
      {
        prop: 'customerIdType',
        label: '证件类型',
        listData: ID_TYPE,
      },
      {
        prop: 'customerIdNum',
        label: '证件号',
      },
      {
        prop: 'vehiclePlate',
        label: '车牌号',
      },
      {
        prop: 'vehiclePlateColor',
        label: '车牌颜色',
        listData: VEHICLE_COLOR_TYPE
      },
      {
        prop: 'cardId',
        label: '卡号',
      },
      {
        prop: 'obuId',
        label: '签号',
      },
      {
        prop: 'amount',
        label: '订单金额',
        funRuleStarts: true,
        funRule: (money: any) => {
          return !money || money === 0 ? '---' : money / 100 + ' 元'
        },
      },
      {
        prop: 'isMigrateData',
        label: '系统来源',
        funRuleStarts: true,
        funRule: (isMigrateData: any) => {
          return isMigrateData == '0' ? '新系统订单' : '老系统订单'
        },
      },
      {
        prop: 'orderStatus', //1 - 已取消 0 - 正常
        label: '订单状态',
        listData: ORDER_STATUS
        // funRuleStarts: true,
        // funRule: (money: any) => {
        //   return money === '0' ? '正常' : '已取消'
        // },
      },
      {
        width: "180px",
        prop: "orderStep", //
        label: "订单阶段",
        funRuleStarts: true,
        funRule: (money: any) => {
          return getLabel(ORDER_STAGE_TYPE, money);
        },
      },
      // {
      //   width: '180px',
      //   prop: 'orderType', //
      //   label: '订单类型',
      //   listData: ORDER_TYPE
      // },
      {
        width: '180px',
        prop: 'artificialStatus', //
        label: '审核类型',
        funRuleStarts: true,
        funRule: (value: any) => {
          return value == '1' ? '人工审核' : '系统审核'
        },
      },
      {
        width: '180px',
        prop: 'auditPerson', //
        label: '审核人',
      },
      {
        width: '150px',
        prop: 'insertTime',
        label: '创建时间',
        funRuleStarts: true,
        funRule: (money: any) => {
          return money ? money.replace('T', ' ') : '---'
        },
      },
    ],
  })

  function getLabel(item, selectedValue) {
    let data = item.value
    let selectedLabel = ''
    for (var i = 0; i < data.length; i++) {
      if (data[i].code == selectedValue) {
        selectedLabel = data[i].name
        break
      }
    }
    return selectedLabel
  }

  function handleInfo(value, row) {
  }

  // 审核
  const check = ref()
  //用户标识
  let cacheAccessToken = getCache(
    'cacheAccessToken',
    { isSessionStorage: false },
    {}
  )
  // console.log(cacheAccessToken, 'cacheAccessToken')

  // 搜索按钮
  function btnSearch() {
    field.value.paging.currentPage = 1
    getList()
  }
  const activeName = ref('1')
  let tageList = [
    // {
    //   label: '全部',
    //   name: null,
    //   value: ''
    // },
    {
      label: '待领取',
      name: '1',
    },
    {
      label: '待审核',
      name: '2',
    },
    // {
    //   label: '审核通过',
    //   name: '2',
    // },
    {
      label: '审核不通过',
      name: '3',
    },
  ]
  //标签分页
  const pass = ref('1')
  function handleClick(tab, event) {
    pass.value = tab.props.name
    if (pass.value == '3') {
      field.value.field[0].hide = false
    } else {
      field.value.field[0].hide = true
    }
    getList()
  }
  // 搜索重置
  function refreshLeft() {
    field.value.paging.currentPage = 1
    searchForm.value = {
      artificialStatus: '',
      orderNo: '',
      productName: '',
      vehiclePlate: '',
      vanType: '',
      orderType: '',
      orderStep: '',
      time: '',
      vehiclePlateColor: '',
      promotionModes: '',
      customerIdNum: '',
      customerTel: ''
    }
    value1.value = null
    getList()
  }
  onMounted(() => {
    getList()
  })
  function getParams() {
    let params: any = {
      methods: 'page',
      pageNo: field.value.paging.currentPage,
      pageSize: field.value.paging.pageSize,
      tabIndex: 0,
      pass: pass.value,
      source: 'WEB',
    }
    if (pass.value == '4') {
      params.operatorId = cacheAccessToken.openId
    }
    //赋值查询参数
    let searchFormList = { ...searchForm.value }
    for (let key in searchFormList) {
      if (searchFormList[key]) {
        params[key] = searchFormList[key]
      }
    }
    if (params.time) {
      params.startTime = dateChange(params.time[0])
      params.endTime = dateChange(params.time[1])
    }
    return params
  }
  function dateChange(time) {
    if (time) {
      time = moment(time).format('YYYY-MM-DD HH:mm:ss')
    }
    return time
  }
  function getList() {
    crudRef.value.tableLoding = true
    BaseService.postN('/managew/api/issue/orderExamine/page', getParams()).then((res: any) => {
      if (res && res.code === 0) {
        //数据转换
        let bizContent = res.data
        let data = bizContent.result || []
        // console.log(data, 'tableData')
        //数据渲染
        tableData.value = data
        crudRef.value.tableLoding = false
        //分页总数
        field.value.paging.total = bizContent.totalCount
      } else {
        crudRef.value.tableLoding = false
        ElMessage.error(res.message)
      }
    })
  }
  function handleCurrentChange(val: number) {
    field.value.paging.currentPage = val
    getList()
  }
  // 领取订单***********************************
  const selectList = ref([])
  // 表格选中
  function selectionChangeHandle(val: any) {
    selectList.value = val.map(item => item.orderId)
  }
  function getOrderFn(type, row?) {
    // if (type == 1 && selectList.value.length == 0) {
    //   ElMessage.warning('请至少选择一条订单领取')
    //   return
    // }
    let orderId: any = []
    // if (type == 1) {
    //   orderId = selectList.value
    // } else {
    //   orderId = [row.orderNo]
    // }
    orderId = row.orderNo
    ElMessageBox.confirm('确认领取订单吗?', '领取提示', {
      confirmButtonText: '确认领取',
      cancelButtonText: '取消',
      type: 'warning',
      draggable: true,
    })
      .then(() => {
        let params = {
          orderNo: orderId,
          // operatorId: cacheAccessToken.openId
        }
        // console.log(params, 'paramsparams')
        BaseService.postN('/managew/api/issue/orderExamine/receive', params).then(
          (res: any) => {
            if (res && res.code === 0) {
              ElMessage.success('领取成功')
              refreshLeft()
            } else {
              ElMessage.error(res.message)
            }
          }
        )
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消领取',
        })
      })
  }
  // 审核*****************************************
  const autdisReasonType = ref()
  function autdisReasonChange(value) {
    autdisReasonType.value = value
  }
  // const autdis = reactive<any>({ auditStatus: 'true', reason: '', reason1: '' }) //审核对象
  const autdis = reactive<any>({ auditStatus: 'true', reason: '' }) //审核对象
  let timer2: any = null
  const form = ref()
  //审核提交
  function checkForm(formEl) {
    if (timer2) return
    timer2 = setTimeout(() => {
      formEl.validate((valid: any, fields: any) => {
        if (valid) {
          // if (autdisReasonType.value == '8' && autdis.reason1) {
          //   autdis.reason = autdis.reason1
          // }
          if (autdis.auditStatus == 'true') {
            autdisReasonType.value = ''
            autdis.reason = ''
            autdis.orderNo = beanData.orderNo
            // autdis.reason1 = ''
          }
          console.log("autdis", autdis)
          BaseService.postN('/managew/api/issue/orderExamine/examine', autdis).then((res: any) => {
            if (res && res.code === 0) {
              ElMessage.success(res.message)
              check.value = false
              visible.value = false
              getList()
            } else {
              ElMessage.error(res.message)
            }
          })
        } else {
          return false
        }
      })
      timer2 = null
    }, 1000)
  }
  function handleAudit() {
    //审核
    autdisReasonType.value = ''
    autdis.auditStatus = 'true'
    autdis.reason = ''
    // autdis.reason1 = ''
    check.value = true
  }

  //审核弹窗
  let beanData: any = {}
  const detailDialogTitle = ref('订单详情')
  const autdisButton = ref(false)
  const offset = ref(150)
  let visible = ref(false)
  const rowData = ref()
  function audit(idx: number, data: any, type) {
    // console.log(type, 'type')
    beanData = data
    detailDialogTitle.value = '订单详情'
    autdisButton.value = type
    BaseService.postN('/managew/api/issue/orderQuery/detail', { orderNo: data.orderNo }).then((res: any) => {
      if (res && res.code === 0) {
        try {
          rowData.value = res.data
        } catch (e) {
          console.log(e)
          ElMessage.error('未知错误')
        } //渲详情数据
        if (rowData) {
          // if (type) {
            // autdis.orderNo = rowData.orderInfo.orderNo
            visible.value = true
          // }
        } else {
          ElMessage.error('没有查到详情数据')
        }
      } else {
        ElMessage.error(res.message)
      }
    })
  }
  //取消
  function cancel() {
    addForm.value = {
      ...initItem,
    }
  }
</script>
<style scoped lang="scsss">

</style>
