<template>
  <zj-tab-page ref="tabPage" :defaultActives="[{ key: 'list', label: $route.meta.title + '-列表', essential: true }]">
    <template slot-scope="{ activeKey, data }">
      <template-page
        v-if="activeKey == 'list'"
        ref="pageRef"
        :get-list="getList"
        :table-attributes="tableAttributes"
        :table-events="tableEvents"
        :options-evens-group="optionsEvensGroup"
        :moreParameters="moreParameters"
        :column-parsing="columnParsing"
        :operation="operation()"
        :exportList="exportList"
        :operationColumnWidth="160"
      >
        <div slot="moreSearch">
          <el-radio-group v-model="examineStatus" size="mini" @change="changeType">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button label="IN">未出库</el-radio-button>
            <el-radio-button label="OUT">已出库</el-radio-button>
          </el-radio-group>
          <br /><br />
        </div>
      </template-page>

      <div v-if="~['add', 'edit'].indexOf(activeKey)" style="box-sizing: border-box; padding: 16px">
        <el-form ref="formRef" :model="formData" :rules="formRules" label-position="left" label-width="80px">
          <div style="font-weight: 500">客户信息</div>
          <el-divider></el-divider>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="销售类型" prop="saleType">
                <el-radio-group v-model="formData.saleType" disabled>
                  <el-radio :label="1">线上销售</el-radio>
                  <el-radio :label="2">线下销售</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="订单编号" prop="orderId">
                <el-input v-model="formData.orderId" autocomplete="off" placeholder="请输入订单编号"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="工单类型" prop="orderSmallType">
                <el-select v-model="formData.orderSmallType" placeholder="请选择">
                  <el-option
                    v-for="item in orderTypeList"
                    :key="item.id"
                    :label="item.orderSmallTypeText"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="工单编号" prop="pgOrderId">
                <el-input v-model="formData.pgOrderId" autocomplete="off" placeholder="请输入工单编号"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="完工时间" prop="overTime">
                <el-date-picker
                  v-model="formData.overTime"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  style="width: 100%"
                  type="date"
                  placeholder="选择日期"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="客户名称" prop="userName">
                <el-input v-model="formData.userName" autocomplete="off" placeholder="请输入客户名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="客户电话" prop="userPhone">
                <el-input v-model="formData.userPhone" autocomplete="off" placeholder="请输入客户电话"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="客户地址" prop="province" :required="true">
                <el-row>
                  <el-col :span="5" style="margin-right: 12px">
                    <el-select
                      v-model="formData.provinceId"
                      placeholder="请选择省"
                      style="width: 100%"
                      @change="changeProvince"
                    >
                      <el-option
                        v-for="item in provinceList.map(v => ({ value: v.id, label: v.name }))"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>
                  </el-col>
                  <el-col :span="5" style="margin-right: 12px">
                    <el-select
                      v-model="formData.cityId"
                      placeholder="请选择市"
                      style="width: 100%"
                      @change="changeCity"
                    >
                      <el-option
                        v-for="item in cityList.map(v => ({ value: v.id, label: v.name }))"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>
                  </el-col>
                  <el-col :span="5" style="margin-right: 12px">
                    <el-select
                      v-model="formData.areaId"
                      placeholder="请选择区"
                      style="width: 100%"
                      @change="changeArea"
                    >
                      <el-option
                        v-for="item in areaList.map(v => ({ value: v.id, label: v.name }))"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>
                  </el-col>
                  <el-col :span="8">
                    <el-select
                      v-model="formData.streetId"
                      placeholder="请选择街道"
                      style="width: 100%"
                      @change="changeStreet"
                    >
                      <el-option
                        v-for="item in streetList.map(v => ({ value: v.id, label: v.name }))"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="" prop="userAddress">
                <el-row :gutter="20">
                  <el-col :span="22">
                    <el-input type="text" v-model="formData.userAddress" placeholder="详细地址"></el-input>
                  </el-col>
                  <el-col :span="2">
                    <geographicalPosi :formData="formData" @selectPosi="selectAddress" />
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input
                  type="textarea"
                  v-model="formData.remark"
                  autocomplete="off"
                  placeholder="请输入备注"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="附件" prop="remark">
                <el-upload
                  class="avatar-uploader"
                  style="height: 122px"
                  :action="baseURL + 'common/upload'"
                  :headers="myHeaders"
                  :show-file-list="false"
                  :on-success="uploadSuccess"
                  :before-upload="beforeUpload"
                >
                  <img v-if="$showImgUrl(formData.fileUrl)" :src="$showImgUrl(formData.fileUrl)" class="avatar" />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <el-tabs v-model="formTabs">
          <el-tab-pane label="旧机信息" name="a"></el-tab-pane>
        </el-tabs>

        <div v-show="formTabs == 'a'">
          <div style="margin-top: 30px">
            <el-button type="primary" size="small" @click="addOld()">添加旧机</el-button>
          </div>

          <el-table
            class="specTable"
            :data="oldList"
            element-loading-text="Loading"
            border
            highlight-current-row
            stripe
            style="margin-top: 20px"
          >
            <el-table-column align="center" label="大类" prop="mainId" min-width="160">
              <template slot-scope="scope">
                <el-select
                  size="small"
                  v-model="scope.row.mainId"
                  filterable
                  placeholder="请选择"
                  @change="changeMain(scope.$index, scope.row)"
                  v-if="scope.row.isEdit"
                >
                  <el-option
                    v-for="item in mainList"
                    :key="item.categoryId"
                    :label="item.name"
                    :value="item.categoryId"
                  >
                  </el-option>
                </el-select>
                <div v-else>{{ scope.row.mainName }}</div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="小类" prop="smallId" min-width="160">
              <template slot-scope="scope">
                <el-select
                  size="small"
                  v-model="scope.row.smallId"
                  filterable
                  placeholder="请选择"
                  @change="changeSmall(scope.$index, scope.row)"
                  v-if="scope.row.isEdit"
                >
                  <el-option
                    v-for="item in smallList"
                    :key="item.categoryId"
                    :label="item.name"
                    :value="item.categoryId"
                  >
                  </el-option>
                </el-select>
                <div v-else>{{ scope.row.smallName }}</div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="规格型号" prop="specId" min-width="160">
              <template slot-scope="scope">
                <el-select
                  size="small"
                  v-model="scope.row.specId"
                  placeholder="请选择"
                  @change="changeSpec(scope.$index, scope.row)"
                  v-if="scope.row.isEdit"
                >
                  <el-option v-for="item in specList" :key="item.id" :label="item.dictName" :value="item.id">
                  </el-option>
                </el-select>
                <div v-else>{{ scope.row.specName }}</div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="属性" prop="attrId" min-width="160">
              <template slot-scope="scope">
                <el-select
                  size="small"
                  v-model="scope.row.attrId"
                  multiple
                  placeholder="请选择"
                  @change="changeAttr(scope.$index, scope.row)"
                  v-if="scope.row.isEdit"
                >
                  <el-option
                    v-for="item in attrList"
                    :key="item.id"
                    :label="item.dictName"
                    :value="item.id"
                    :disabled="
                      panduanduoxuandanxuan(attrList, item, scope.row.attrId) && !~scope.row.attrId.indexOf(item.id)
                    "
                  >
                    {{ `${item.categoryName} - ${item.dictName}` }}
                  </el-option>
                </el-select>
                <div v-else>{{ scope.row.attrName.join('、') }}</div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="单位" min-width="120">
              <template>台</template>
            </el-table-column>
            <el-table-column align="center" label="数量" prop="num" min-width="120">
              <template slot-scope="scope">
                <el-input size="small" v-model="scope.row.num" v-if="scope.row.isEdit"></el-input>
                <div v-else>{{ scope.row.num }}</div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="金额" prop="payAmount" min-width="120">
              <template slot-scope="scope">
                <el-input size="small" v-model="scope.row.payAmount" v-if="scope.row.isEdit"></el-input>
                <div v-else>{{ scope.row.payAmount }}</div>
              </template>
            </el-table-column>

            <el-table-column align="center" label="操作" min-width="120" fixed="right">
              <template slot-scope="scope">
                <el-button type="text" @click="saveOld(scope.$index, scope.row)" v-if="scope.row.isEdit"
                  >保存</el-button
                >
                <el-button type="text" @click="editOld(scope.$index, scope.row)" v-else>编辑</el-button>
                <el-popconfirm title="确定删除吗？" @confirm="deleteOld(scope.$index)" style="margin-left: 10px">
                  <el-button slot="reference" type="text">删除</el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div slot="footer" class="dialog-footer" style="margin-top: 20px">
          <el-button size="mini" @click="data.removeTab()">取 消</el-button>
          <el-button size="mini" @click="formConfirm(data.removeTab)" type="primary">确 定</el-button>
        </div>
      </div>

      <div v-if="~['detail'].indexOf(activeKey)" style="box-sizing: border-box; padding: 16px">
        <div style="font-weight: 500">客户信息</div>
        <el-divider></el-divider>

        <el-descriptions border title="" :column="4" :colon="false" labelStyle="width: 8%" contentStyle="width: 17%">
          <el-descriptions-item label="销售类型">
            {{ { 1: '线上销售', 2: '线下销售' }[detailData.saleType] }}
          </el-descriptions-item>
          <el-descriptions-item label="订单单号">
            {{ detailData.orderId }}
          </el-descriptions-item>
          <el-descriptions-item label="工单类型">
            {{ detailData.orderSmallTypeText }}
          </el-descriptions-item>
          <el-descriptions-item label=""> </el-descriptions-item>
        </el-descriptions>
        <el-descriptions
          border
          title=""
          :column="4"
          :colon="false"
          labelStyle="width: 8%"
          contentStyle="width: 17%"
          style="margin-top: -1px"
        >
          <el-descriptions-item label="订单单号">
            {{ detailData.pgOrderId }}
          </el-descriptions-item>
          <el-descriptions-item label="完工时间">
            {{ detailData.overTime }}
          </el-descriptions-item>
          <el-descriptions-item label="客户姓名">
            {{ detailData.userName }}
          </el-descriptions-item>
          <el-descriptions-item label="客户电话">
            {{ detailData.userPhone }}
          </el-descriptions-item>
        </el-descriptions>
        <el-descriptions
          border
          title=""
          :column="1"
          :colon="false"
          labelStyle="width: 8%"
          contentStyle="width: 92%"
          style="margin-top: -1px"
        >
          <el-descriptions-item label="详细地址">
            {{ detailData.province }}{{ detailData.city }}{{ detailData.area }}{{ detailData.street
            }}{{ detailData.userAddress }}
          </el-descriptions-item>
        </el-descriptions>
        <el-descriptions
          border
          title=""
          :column="1"
          :colon="false"
          labelStyle="width: 8%"
          contentStyle="width: 92%"
          style="margin-top: -1px"
        >
          <el-descriptions-item label="附件">
            <el-image
              v-if="detailData.fileUrl"
              style="width: 100px; height: 100px"
              :src="$showImgUrl(detailData.fileUrl)"
              :preview-src-list="[$showImgUrl(detailData.fileUrl)]"
            >
            </el-image>
          </el-descriptions-item>
          <el-descriptions-item label="备注">
            {{ detailData.remark }}
          </el-descriptions-item>
        </el-descriptions>

        <el-tabs v-model="detailTabs" style="margin-top: 30px">
          <el-tab-pane label="旧机信息" name="a"></el-tab-pane>
        </el-tabs>

        <div v-show="detailTabs == 'a'">
          <el-table
            class="specTable"
            :data="detailData.itemList"
            element-loading-text="Loading"
            border
            highlight-current-row
            stripe
            style="margin-top: 20px"
          >
            <el-table-column align="center" label="大类" prop="mainName" min-width="160"></el-table-column>
            <el-table-column align="center" label="小类" prop="smallName" min-width="160"></el-table-column>
            <el-table-column align="center" label="规格型号" prop="specName" min-width="160"></el-table-column>
            <el-table-column align="center" label="属性" prop="attrId" min-width="160">
              <template slot-scope="scope">
                {{ scope.row.oldProductManagerItemAttributes.map(o => o.dictName).join('、') }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="单位" min-width="120">
              <template>台</template>
            </el-table-column>
            <el-table-column align="center" label="数量" prop="num" min-width="120"></el-table-column>
            <el-table-column align="center" label="金额" prop="payAmount" min-width="120"></el-table-column>
          </el-table>
        </div>

        <div slot="footer" class="dialog-footer" style="margin-top: 20px">
          <el-button size="mini" @click="data.removeTab()">关 闭</el-button>
        </div>
      </div>
    </template>
  </zj-tab-page>
</template>

<script>
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
import { lbsAmapRegion } from '@/api/common.js'
import TemplatePage from '@/components/template/template-page-1.vue'
import import_mixin from '@/components/template/import_mixin.js'
import { required, mobileRequired, mobile } from '@/components/template/rules_verify.js'
import {
  getList,
  listExport,
  addData,
  editData,
  getDetail,
  outData,
  getOrderTypeList,
  getCategoryList,
  getAttrList
} from '@/api/old_machine'
import operation_mixin from '@/components/template/operation_mixin.js'
import geographicalPosi from '@/components/geographicalPosi/index.vue'

export default {
  components: { TemplatePage, geographicalPosi },
  mixins: [import_mixin, operation_mixin],

  data() {
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback('请输入手机号')
      } else if (!/^1[3456789]\d{9}$/.test(value)) {
        callback('请输入正确的手机号')
      } else {
        callback()
      }
    }
    return {
      baseURL: process.env.VUE_APP_BASE_API,
      myHeaders: { 'x-token': getToken() },
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: true
      },
      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      // 勾选选中行
      recordSelected: [],
      /** 表单变量 */
      formDialogType: 0,
      formDialogTitles: ['新增', '编辑'],
      formDialog: false,
      formData: {
        id: '',
        companyName: '', // 所属商户
        saleType: 2, // 销售类型
        orderId: '', // 订单编号
        orderSmallType: '', // 工单类型
        pgOrderId: '', // 工单编号
        overTime: '', // 完工时间
        userName: '', // 客户名称
        userPhone: '', // 客户电话
        lng: '',
        lat: '',
        province: '',
        provinceId: '',
        city: '',
        cityId: '',
        area: '',
        areaId: '',
        street: '',
        streetId: '',
        userAddress: '',
        remark: '', // 备注
        fileUrl: '' // 附件
      },
      formRules: {
        userName: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
        userPhone: [{ required: true, validator: validatePhone, trigger: 'blur' }]
      },
      formType: 'add',
      formVisible: false,

      examineStatus: '',
      orderTypeList: [],
      provinceList: [],
      cityList: [],
      areaList: [],
      streetList: [],
      goodsList: [],
      goodsSpecList: [],
      goodsSelectList: [],

      detailData: {},
      examineFormData: {
        status: '',
        remark: ''
      },
      examineFormRules: {
        status: [{ required: true, message: '请选择审批结果', trigger: 'change' }],
        remark: [{ required: true, message: '请输入审批备注', trigger: 'blur' }]
      },

      showCodeDialog: false,
      timer: '',

      pageType: '',

      formTabs: 'a',
      detailTabs: 'a',

      oldList: [], // 旧机列表
      mainList: [],
      smallList: [],
      specList: [],
      attrList: []
    }
  },

  computed: {
    ...mapGetters(['name']),
    // 事件组合
    optionsEvensGroup() {
      return [
        [
          [
            this.optionsEvensAuth('add', {
              click: () => {
                this.openForm('add')
              }
            })
          ]
        ],
        [
          [
            this.optionsEvensAuth('out', {
              name: '批量出库',
              click: () => {
                this.batchOut()
              }
            })
          ]
        ]
      ]
    },
    // 更多参数
    moreParameters() {
      return []
    }
  },

  create() {},

  methods: {
    // 列表请求函数
    // getList: getList,
    getList(p) {
      try {
        var pam = JSON.parse(JSON.stringify(p))
        if (this.examineStatus) {
          pam.params.push({ param: 'a.status', compare: '=', value: this.examineStatus })
        }
        return getList(pam)
      } catch (error) {
        console.log(error)
      }
    },
    // 列表导出函数
    exportList: listExport,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },
    // 切换状态
    changeType(val) {
      this.$refs.pageRef.refreshList()
    },
    // 表格操作列
    operation() {
      return this.operationBtn({
        edit: {
          conditions: ({ row, index, column }) => {
            return row.status == 'IN'
          },
          btnType: 'text',
          click: ({ row, index, column }) => {
            this.openForm('edit', row.id)
          }
        },
        detail: {
          btnType: 'text',
          click: ({ row, index, column }) => {
            this.openDetail('detail', row.id)
          }
        },
        out: {
          conditions: ({ row, index, column }) => {
            return row.status == 'IN'
          },
          btnType: 'text',
          prompt: '确定出库吗？',
          click: ({ row, index, column }) => {
            outData({ oldManagerId: row.id }).then(() => {
              this.$message({ type: 'success', message: '出库成功!' })
              this.$refs.pageRef.refreshList()
            })
          }
        },
        orderDetail: {
          conditions: ({ row, index, column }) => {
            return row.saleType == 1
          },
          btnType: 'text',
          click: ({ row, index, column }) => {
            this.$router.push({
              name: 'order_detail',
              query: {
                orderId: row.orderId
              }
            })
          }
        }
      })
    },
    openForm(type, id) {
      this.$refs.tabPage.addTab({
        // 对应显示的模块
        activeKey: type,
        // 唯一标识
        key: type,
        // 页签名称
        label: { add: '新增', edit: '编辑' }[type],
        // 打开时事件
        triggerEvent: () => {
          this.pageType = type
          this.formCancel()
          this.$nextTick(() => {
            this.getOrderTypeList()
            this.formType = type
            this.formVisible = true
            if (type == 'add') {
              this.formDialogType = 0
              this.formData.companyName = this.name
              this.getinitlbslist()
            } else if (type == 'edit') {
              this.formDialogType = 1
              getDetail({ oldManagerId: id }).then(res => {
                const data = res.data

                this.formData = Object.keys(this.formData).reduce((result, key) => {
                  if (data.hasOwnProperty(key)) {
                    result[key] = data[key]
                  } else {
                    result[key] = this.formData[key]
                  }
                  return result
                }, {})

                if (data.itemList?.length > 0) {
                  this.oldList = data.itemList.map(item => {
                    return {
                      isEdit: false,
                      mainId: item.mainId,
                      mainName: item.mainName,
                      smallId: item.smallId,
                      smallName: item.smallName,
                      specId: item.specId,
                      specName: item.specName,
                      attrId: item.oldProductManagerItemAttributes.map(o => o.goodsCategoryItemId),
                      attrName: item.oldProductManagerItemAttributes.map(o => o.dictName),
                      num: item.num,
                      payAmount: item.payAmount
                    }
                  })
                }
                this.getinitlbslist()
              })
            }
          })
        },
        // 关闭时事件
        closeEvent: () => {
          this.formCancel()
        }
      })
    },

    formCancel() {
      this.formVisible = false
      this.$refs?.formRef?.resetFields()
      this.formData.id = ''
      this.formData.province = ''
      this.formData.provinceId = ''
      this.formData.city = ''
      this.formData.cityId = ''
      this.formData.area = ''
      this.formData.areaId = ''
      this.formData.street = ''
      this.formData.streetId = ''
      this.formData.fileUrl = ''
      this.oldList = []
      this.$data.formRef = this.$options.data().formRef
    },

    formConfirm(cancel) {
      this.$refs.formRef.validate((valid, invalidFields, errLabels) => {
        if (valid) {
          if (this.oldList.some(o => o.isEdit)) return this.$errorMsg('旧机信息存在未保存信息')

          let orderSmallTypeText = this.formData.orderSmallType
            ? this.orderTypeList.find(o => o.id == this.formData.orderSmallType).orderSmallTypeText
            : ''
          let oldList = this.oldList.map(item => {
            return {
              id: item.specId,
              itemIds: item.attrId,
              num: item.num,
              payAmount: item.payAmount
            }
          })

          if (this.formDialogType == 0) {
            addData({
              ...this.formData,
              overTime:
                this.formData.overTime.length == 10 ? this.formData.overTime + ' 00:00:00' : this.formData.overTime,
              orderSmallTypeText,
              orderOldProductAdds: oldList
            }).then(res => {
              this.$message({ type: 'success', message: `${this.formDialogTitles[this.formDialogType]}成功!` })
              cancel('list')
              this.$refs.pageRef.refreshList()
            })
          } else {
            editData({
              ...this.formData,
              overTime:
                this.formData.overTime.length == 10 ? this.formData.overTime + ' 00:00:00' : this.formData.overTime,
              orderSmallTypeText,
              orderOldProductAdds: oldList
            }).then(res => {
              this.$message({ type: 'success', message: `${this.formDialogTitles[this.formDialogType]}成功!` })
              cancel('list')
              this.$refs.pageRef.refreshList()
            })
          }
        }
      })
    },

    openDetail(type, id) {
      this.$refs.tabPage.addTab({
        // 对应显示的模块
        activeKey: type,
        // 唯一标识
        key: type,
        // 页签名称
        label: { detail: '详情' }[type],
        // 打开时事件
        triggerEvent: () => {
          this.pageType = type
          this.formCancel()
          this.$nextTick(() => {
            this.detailTabs = 'a'
            if (type == 'detail') {
              this.formDialogType = 0
            }
            getDetail({ oldManagerId: id }).then(res => {
              this.detailData = res.data
            })
          })
        },
        // 关闭时事件
        closeEvent: () => {
          this.detailCancel()
        }
      })
    },
    detailCancel() {
      this.formVisible = false
      this.$refs?.examineForm?.resetFields()
      this.$data.examineForm = this.$options.data().examineForm
    },
    detailConfirm(cancel) {
      this.$refs.examineForm.validate((valid, invalidFields, errLabels) => {
        if (valid) {
          outData({
            orderId: this.detailData.orderId,
            examineStatus: this.examineFormData.status,
            examineRemark: this.examineFormData.remark
          }).then(res => {
            if (this.examineFormData.status == 'OK' && res.data.codeUrl) {
              this.creatCode(res.data.codeUrl, this.detailData.orderId)
            } else {
              this.$message({ type: 'success', message: `审批成功!` })
              cancel('list')
              this.$refs.pageRef.refreshList()
            }
          })
        }
      })
    },

    // 附件 - 上传成功
    uploadSuccess(res, file) {
      this.formData.fileUrl = res.data.url
    },

    // 附件 - 上传前
    beforeUpload(file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1)
      const whiteList = ['jpg', 'jpeg', 'png']
      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$errorMsg('只支持上传jpg/png文件!')
        return false
      }
    },

    getinitlbslist() {
      // 初始化请求省市区街道下拉选项数据
      lbsAmapRegion({ pid: 0 }).then(res => {
        this.provinceList = res.data
        if (this.formData.province) {
          var provinceItem = this.provinceList.find(o => o.name === this.formData.province)
          if (provinceItem) {
            this.formData.provinceId = provinceItem.id
          }
          lbsAmapRegion({ pid: this.formData.provinceId }).then(res => {
            this.cityList = res.data
            if (this.formData.city) {
              var cityItem = this.cityList.find(o => o.name === this.formData.city)
              if (cityItem) {
                this.formData.cityId = cityItem.id
              }
              lbsAmapRegion({ pid: this.formData.cityId }).then(res => {
                this.areaList = res.data
                if (this.formData.area) {
                  var areaItem = this.areaList.find(o => o.name === this.formData.area)
                  if (areaItem) {
                    this.formData.areaId = areaItem.id
                  }
                  lbsAmapRegion({ pid: this.formData.areaId }).then(res => {
                    this.streetList = res.data
                    if (this.formData.street) {
                      var streetItem = this.streetList.find(o => o.name === this.formData.street)
                      if (streetItem) {
                        this.formData.streetId = streetItem.id
                      }
                    }
                  })
                }
              })
            }
          })
        }
      })
    },

    delDataK(num) {
      if (num <= 1) {
        // 删除市
        this.formData.cityId = ''
        this.formData.city = ''
        // 删除市选项
        this.cityList = []
      }
      if (num <= 2) {
        // 删除区
        this.formData.areaId = ''
        this.formData.area = ''
        // 删除区选项
        this.areaList = []
      }
      if (num <= 3) {
        // 删除街道
        this.formData.streetId = ''
        this.formData.street = ''
        // 删除街道选项
        this.streetList = []
      }
      // 删除gps地址
      this.formData.gpsAddress = ''
    },

    // 更改省
    changeProvince(val) {
      // 获取省名称
      this.formData.province = this.provinceList.find(item => item.id === val)?.name || ''
      // 清除市区街道以及详细地址数据
      this.delDataK(1)
      lbsAmapRegion({ pid: val }).then(res => {
        this.cityList = res.data
      })
    },

    // 更改市
    changeCity(val) {
      // 获取市名称
      this.formData.city = this.cityList.find(item => item.id === val).name
      // 清除区街道以及详细地址数据
      this.delDataK(2)
      lbsAmapRegion({ pid: val }).then(res => {
        this.areaList = res.data
      })
    },

    // 更改区
    changeArea(val) {
      // 获取区名称
      this.formData.area = this.areaList.find(item => item.id === val).name
      // 清除街道以及详细地址数据
      this.delDataK(3)
      lbsAmapRegion({ pid: val }).then(res => {
        this.streetList = res.data
      })
    },

    // 更改街道
    changeStreet(val) {
      // 获取街道名称
      this.formData.street = this.streetList.find(item => item.id === val).name
      // 清除详细地址数据
      this.delDataK(4)
    },

    selectAddress(data) {
      console.log(data)
      this.formData.lng = data.center[0]
      this.formData.lat = data.center[1]
      // 获取定位的省市区街道
      var { province, city, district, township } = data.data.addressComponent
      // 获取选中省名称id
      var { id, name } = this.provinceList.find(item => item.name === province)
      this.formData.provinceId = id
      this.formData.province = name
      // 请求市选项
      lbsAmapRegion({ pid: this.formData.provinceId }).then(res => {
        // 赋值市选项
        this.cityList = res.data
        // 获取选中市名称id
        var { id, name } = res.data.find(item => item.name === city)
        this.formData.cityId = id
        this.formData.city = name
        // 请求区选项
        lbsAmapRegion({ pid: this.formData.cityId }).then(res => {
          // 赋值区选项
          this.areaList = res.data
          // 获取选中区名称id
          var { id, name } = res.data.find(item => item.name === district)
          this.formData.areaId = id
          this.formData.area = name
          // 请求街道选项
          lbsAmapRegion({ pid: this.formData.areaId }).then(res => {
            // 赋值街道选项
            this.streetList = res.data
            // 获取选中街道名称id
            var { id, name } = res.data.find(item => item.name === township)
            this.formData.streetId = id
            this.formData.street = name
            // 赋值GPS详细地址
            this.formData.userAddress = data.name
          })
        })
      })
    },

    batchOut() {
      if (this.recordSelected && this.recordSelected.length > 0) {
        let ids = []
        this.recordSelected.forEach(value => {
          ids.push(value.id)
        })
        outData({ oldManagerId: ids.join(',') }).then(() => {
          this.$message({ type: 'success', message: '出库成功!' })
          this.$refs.pageRef.refreshList()
        })
      } else {
        this.$errorMsg('请选择')
      }
    },

    // 获取工单类型列表
    getOrderTypeList() {
      getOrderTypeList({
        pageNum: 1,
        pageSize: -1,
        params: [{ param: 'a.status', compare: '=', value: true }]
      }).then(res => {
        this.orderTypeList = res.data.records
      })
    },

    // 获取类目列表
    getCategoryList() {
      return new Promise((resolve, reject) => {
        getCategoryList().then(res => {
          this.mainList = res.data
          resolve(1)
        })
      })
    },

    // 获取规格/属性列表
    getAttrList(smallId) {
      getAttrList({
        pageNum: 1,
        pageSize: -1,
        params: [
          { param: 'small_id', compare: '=', value: smallId },
          { param: 'status', compare: '=', value: 'ON' }
        ]
      }).then(res => {
        this.specList = res.data.records.filter(o => o.typeAttribute == 'SPEC')
        this.attrList = res.data.records.filter(o => o.typeAttribute == 'OTHER')
      })
    },

    panduanduoxuandanxuan(list, data, vals) {
      if (data.typeOption === 'SIGIN') {
        return !!list.filter(item => !!~vals.indexOf(item.id) && item.serviceCategoryId === data.serviceCategoryId)
          .length
      } else {
        return false
      }
    },

    // 添加旧机
    addOld() {
      if (this.oldList.some(o => o.isEdit)) return this.$errorMsg('旧机信息存在未保存信息')

      this.getCategoryList()
      let obj = {
        isEdit: true,
        mainId: '',
        mainName: '',
        smallId: '',
        smallName: '',
        specId: '',
        specName: '',
        attrId: [],
        attrName: [],
        num: '',
        payAmount: ''
      }
      let item = JSON.parse(JSON.stringify(obj))
      this.oldList.push(item)
    },

    // 编辑旧机
    async editOld(index, row) {
      if (this.oldList.some(o => o.isEdit)) return this.$errorMsg('旧机信息存在未保存信息')

      this.oldList[index].isEdit = true
      await this.getCategoryList()
      this.smallList = this.mainList.find(o => o.categoryId == row.mainId).children
      this.getAttrList(row.smallId)
    },

    // 保存旧机
    saveOld(index) {
      const data = this.oldList[index]
      if (!data.mainId) return this.$errorMsg('请选择大类')
      if (!data.smallId) return this.$errorMsg('请选择小类')
      if (!data.specId) return this.$errorMsg('请选择规格型号')
      if (!data.num) return this.$errorMsg('请输入数量')
      if (!data.payAmount) return this.$errorMsg('请输入金额')

      this.oldList[index].isEdit = false
      this.mainList = []
      this.smallList = []
      this.specList = []
      this.attrList = []
    },

    // 删除旧机
    deleteOld(index) {
      this.oldList.splice(index, 1)
    },

    // 切换大类
    changeMain(index, row) {
      this.oldList[index].mainName = this.mainList.find(o => o.categoryId == row.mainId).name
      this.smallList = this.mainList.find(o => o.categoryId == row.mainId).children

      this.oldList[index].smallId = ''
      this.oldList[index].specId = ''
      this.oldList[index].attrId = []
      this.specList = []
      this.attrList = []
    },

    // 切换小类
    changeSmall(index, row) {
      this.oldList[index].smallName = this.smallList.find(o => o.categoryId == row.smallId).name

      this.oldList[index].specId = ''
      this.oldList[index].attrId = []
      this.specList = []
      this.attrList = []
      this.getAttrList(row.smallId)
    },

    // 切换规格
    changeSpec(index, row) {
      this.oldList[index].specName = this.specList.find(o => o.id == row.specId).dictName
    },

    // 切换属性
    changeAttr(index, row) {
      let names = []
      // 遍历对象数组
      this.attrList.forEach(obj => {
        // 如果当前对象的ID在ID数组中
        if (row.attrId.includes(obj.id)) {
          // 将当前对象的name属性添加到names数组中
          names.push(obj.dictName)
        }
      })
      this.oldList[index].attrName = names
    }
  }
}
</script>

<style lang="scss">
.specTable .el-table__cell {
  padding: 0 !important;
}

// 图片墙
.el-upload-list--picture-card .el-upload-list__item {
  width: 100px;
  height: 100px;
}

.el-upload--picture-card {
  width: 100px;
  height: 100px;
  line-height: 100px;

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
}
</style>
