<template>
  <el-dialog
    v-loading="loading"
    :title="title"
    :center="true"
    align="left"
    top="8vh"
    width="1040px"
    :close-on-click-modal="false"
    :visible.sync="showModelThis"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    append-to-body
    @close="showModelThis = false"
  >
    <el-card style="margin-top: -25px">
      <upload-excel :on-success="handleSuccess" :before-upload="beforeUpload" />
      <el-form ref="ruleForm" :model="ruleForm" :size="'mini'">
        <el-table
          :data="ruleForm.order_addr"
          border
          :size="'mini'"
          style="width: 100%"
          max-height="400px"
          row-key="key"
        >
          <el-table-column
            prop="receipt_quantity"
            label="收货总数"
            width="100"
            show-overflow-tooltip
          />

          <el-table-column
            prop="contactor"
            label="收件联系人"
            show-overflow-tooltip
            width="85"
          />

          <el-table-column
            prop="mobile"
            label="收货联系电话"
            show-overflow-tooltip
            width="100"
          />
          <el-table-column
            show-overflow-tooltip
            prop="in_addr"
            label="收货省市区(文件导入)"
            width="150"
          />
          <el-table-column
            show-overflow-tooltip
            prop="addr_code_name"
            label="收货省市区(系统解析)"
            width="150"
          />
          <el-table-column prop="addr" label="详细地址" show-overflow-tooltip />

          <el-table-column fixed="right" width="80" label="操作">
            <template slot-scope="scope">
              <el-tooltip effect="dark" content="编辑" placement="top">
                <i class="el-icon-edit tb-icon" @click="openHouseModal(scope.$index)" />
              </el-tooltip>
              <el-tooltip effect="dark" content="删除" placement="top">
                <i
                  class="el-icon-delete tb-icon"
                  @click="deleteRow(scope.$index, ruleForm.order_addr)"
                />
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div class="tr" style="padding: 10px 0 0 0">
        <el-button type="primary" size="small" @click="submitForm">保 存 </el-button>
      </div>
    </el-card>
  </el-dialog>
</template>
<script>
import resToken from '@/mixins/resToken'
import { province_list, city_list, county_list } from '@/assets/js/area-data'
import {
  isnumber,
  isMobile,
  isChinese,
  isEmoticon,
  isSpecialSymbol,
  hasSpace,
  isAddr
} from '@/utils/validate'
export default {
  name: 'InAddrModel',
  mixins: [resToken],
  props: ['showModel', 'id', 'sitem'],
  data() {
    const validatemobile = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('联系电话不能为空！'))
      } else {
        if (!isMobile(value)) {
          callback(new Error('联系电话格式不正确！'))
        } else {
          callback()
        }
      }
    }
    const validateWeight = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('收货总数不能为空!'))
      } else {
        if (!isnumber(value)) {
          callback(new Error('收货总数仅支持整数!'))
        } else {
          callback()
        }
      }
    }
    const validatecontactor = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('联系人不能为空！'))
      } else {
        if (value.length < 2 || value.length > 10) {
          callback(new Error('联系人规则为2~10位汉字！'))
        } else {
          const isOk = value.split("").every(s => isChinese(s) || /^[A-Za-z]+$/.test(s));
          if (!isOk) {
            callback(new Error('联系人规则为2~10位汉字！'))
          } else if (isEmoticon(value)) {
            callback(new Error('联系人规则为2~10位汉字！'))
          } else {
            callback()
          }
        }
      }
    }
    const validateAddr = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('详细地址不能为空！'))
      } else {
        if (hasSpace(value)) {
          callback(new Error('系统不允许输入转义字符，请检查后重新输入！'))
        } else if (isSpecialSymbol(value)) {
          callback(new Error('不能使用英文特殊字符！'))
        } else if (isAddr(value)) {
          callback()
        } else {
          callback(new Error('详细地址填写不规范！'))
        }
      }
    }
    return {
      showAddrAddEditModal: false,
      AddrAddEditModalIndex: -1,
      AddrAddEditModalSitem: {},
      tableData: [],
      tableHeader: [],
      title: '',
      showModelThis: false,
      loading: false,
      newTime: 0,
      pickerOptions: {
        disabledDate: (time) => {
          return time.getTime() < new Date().valueOf()
        }
      },
      rulesThis: this.rules,
      ruleForm: {
        order_addr: [] // 收货地址
      },
      rules: {
        receipt_quantity: [
          {
            required: true,
            validator: validateWeight,
            trigger: 'blur'
          }
        ],

        contactor: [
          {
            required: true,
            trigger: 'blur',
            validator: validatecontactor
          }
        ],
        mobile: [
          {
            required: true,
            validator: validatemobile,
            trigger: 'blur'
          }
        ],
        addr_code: [
          {
            type: 'array',
            required: false,
            trigger: 'change'
          }
        ],
        addr: [
          {
            required: true,
            validator: validateAddr,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  watch: {
    showModel: function(val) {
      this.showModelThis = val
      if (val) {
        this.initForm()
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit('cancel')
        this.$emit('update:showModel', val)
      }
    }
  },
  mounted() {
    this.get_code()
  },
  methods: {
    async resetForm() {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields()
          this.$refs.ruleForm.clearValidate()
          this.ruleForm = {
            order_addr: []
          }
        }
      })
    },
    // 省市区删除行操作
    deleteRow(index, rows) {
      rows.splice(index, 1)
    },
    showAddrAddEditModalRefresh(e) {
      const { index, item } = e

      if (index === -1) {
        this.ruleForm.order_addr.push(JSON.parse(JSON.stringify(item)))
      } else {
        const {
          receipt_quantity,
          contactor,
          mobile,
          addr_code,
          addr_code_name,
          addr,
          id
        } = JSON.parse(JSON.stringify(item))
        this.ruleForm.order_addr[index].receipt_quantity = receipt_quantity
        this.ruleForm.order_addr[index].contactor = contactor
        this.ruleForm.order_addr[index].mobile = mobile
        this.ruleForm.order_addr[index].addr_code = addr_code
        this.ruleForm.order_addr[index].addr_code_name = addr_code_name
        this.ruleForm.order_addr[index].addr = addr
        this.ruleForm.order_addr[index].id = id
      }
      this.$refs.ruleForm.validateField('order_addr')
    },
    beforeUpload(file) {
      const isLt1M = file.size / 1024 < 500
      if (isLt1M) {
        return true
      }
      this.$message({
        message: '请不要上传大于500KB的文件.',
        type: 'warning'
      })
      return false
    },
    handleSuccess({ results, header }) {
      if (results.length === 0) {
        this.$message.error('表格无有效数据！')
        return
      }
      if (results.length > 500) {
        this.$message.error('地址数据不能超过500条！')
        return
      }
      const head = [
        '收货总数',
        '收货联系人',
        '收货联系电话',
        '收货省名称',
        '收货市名称',
        '收货区名称',
        '详细地址'
      ]
      if (head.length !== header.length) {
        this.$message.error('表头与导入模板不匹配！')
        return
      }
      let hederOk = true
      head.forEach((v1, i1) => {
        if (v1 !== header[i1].replace(/\s*/g, '')) {
          hederOk = false
        }
      })

      if (!hederOk) {
        this.$message.error('表头与导入模板不匹配！')
        return
      }
      this.tableHeader = header
      this.tableData = []
      const list = results
      const tableOk = true
      this.ruleForm.order_addr = []
      list.forEach((v1) => {
        const b = Object.values(v1)
        const item = this.get_code(b[3], b[4], b[5])
        const model = {
          receipt_quantity: b[0] + '',
          contactor: b[1] + '',
          mobile: b[2] + '',
          in_addr: b[3] + '/' + b[4] + '/' + b[5],
          addr_code_name: item.name + '',
          addr_code: item.code,
          addr: b[6] + '',
          edit: false
        }
        this.ruleForm.order_addr.push(model)
      })
      if (!tableOk) {
        this.$message.error('最晚收货日期不正确，请将表格格式转为文本上传！')
      }
    },
    openHouseModal(index) {
      this.AddrAddEditModalIndex = index

      if (index === -1) {
        this.AddrAddEditModalSitem = {}
      } else {
        this.AddrAddEditModalSitem = JSON.parse(
          JSON.stringify(this.ruleForm.order_addr[index])
        )
      }
      this.showAddrAddEditModal = true
      // let findex = this.ruleForm.order_addr.findIndex((v) => v.edit === true);
      // if (findex !== -1) {
      //   this.$message.warning("当前已有地址在编辑，请保存后再试！");
      //   return;
      // } else {
      //   this.ruleForm.order_addr[index].edit = true;
      // }
    },
    unique(arr) {
      const hash = []
      for (let i = 0; i < arr.length; i++) {
        const index = hash.findIndex((v1) => v1.inv_number === arr[i].inv_number)
        if (index === -1) {
          hash.push(arr[i])
        }
      }
      return hash
    },
    setTime(time) {
      time = time.replace(/\//g, '-')
      time = time.replace(/\./g, '-')
      const key = new Date(time).valueOf() + ''
      if (key.length !== 13) {
        time = ''
      }
      return time
    },
    async initForm() {
      this.rulesThis = this.rules
      await this.resetForm()
      this.newTime = 0
      this.loading = true
      this.tableData = []
      this.tableHeader = []
      this.step = 1
      this.title = '批量导入收货地址信息'

      this.changea()
      this.loading = false
    },
    refreshAll() {
      this.showModelThis = false
      this.$emit('refresh')
    },
    changea() {
      this.newTime = new Date().valueOf()
    },

    async submitForm() {
      const { order_addr } = this.ruleForm
      if (order_addr.length < 1) {
        this.$message.error('导入数据不能为空！')
        this.loading = false
        return
      }
      let isEdit = false
      order_addr.forEach((v) => {
        v.err = false
        if (v.edit) {
          v.err = true
          isEdit = true
        }
      })
      if (isEdit) {
        this.$message.error('当前收货地址已在编辑，请保存后再试！')
        this.loading = false
        return
      }
      let cItem = null
      order_addr.some((x, i) => {
        cItem = this.checkItem(x)
        if (!cItem.isok) {
          cItem.index = i
          return true
        }
      })
      if (cItem && !cItem.isok) {
        this.$message.error(`第${cItem.index + 1}行,${cItem.message}`)
        this.loading = false
        return
      }
      const list = JSON.parse(JSON.stringify(order_addr))
      this.$emit('refresh', { list: list })
    },
    checkItem(sitem) {
      const model = {
        isok: true,
        message: ''
      }
      const { arrive_time, receipt_quantity, contactor, mobile, addr_code, addr } = sitem
      if (receipt_quantity === '' && model.isok) {
        model.isok = false
        model.message = '收货总数不能为空!'
      }
      if (!isnumber(receipt_quantity) && model.isok) {
        model.isok = false
        model.message = '收货总数仅支持整数!'
      }
      if (arrive_time === '' && model.isok) {
        model.isok = false
        model.message = '最晚收货日期不能为空!'
      }

      if (contactor === '' && model.isok) {
        model.isok = false
        model.message = '收货联系人不能为空!'
      }
      if (mobile === '' && model.isok) {
        model.isok = false
        model.message = '收货联系电话不能为空!'
      }
      if (!isMobile(mobile) && model.isok) {
        model.isok = false
        model.message = '收货联系电话格式不正确!'
      }
      // if (addr_code.length !== 3 && model.isok) {
      //   model.isok = false;
      //   model.message = "收货省市区不能为空!";
      // }
      if (addr === '' && model.isok) {
        model.isok = false
        model.message = '详细地址不能为空!'
      }
      return model
    },
    get_code(name1, name2, name3) {
      let name = ''
      let code = []
      if (name1 && name2 && name3) {
        for (const x in province_list) {
          if (name1 === province_list[x]) {
            code.push(x)
            name += province_list[x]
            break
          }
        }
        if (code.length === 1) {
          for (const y in city_list) {
            if (name2 === city_list[y]) {
              code.push(y)
              name += '/' + city_list[y]
              break
            }
          }
        }
        if (code.length === 2) {
          for (const z in county_list) {
            if (name3 === county_list[z]) {
              code.push(z)
              name += '/' + county_list[z]
              break
            }
          }
        }

        if (code.length === 3) {
          let str1 = ''
          let str2 = ''
          let isok = false
          str1 = code[0].slice(0, 2)
          str2 = code[1].slice(2, 4)
          if (
            code[1].indexOf(str1) === 0 &&
            code[2].indexOf(str1) === 0 &&
            code[2].indexOf(str2) == 2
          ) {
            isok = true
          }
          if (!isok) {
            name = ''
            code = []
          }
        } else {
          name = ''
          code = []
        }
      }
      return { name: name, code: code }
    }
  }
}
</script>

<style lang="scss" scoped>
.account {
  .gongshi {
    span {
      vertical-align: top;
      display: inline-block;
      color: #000;
    }
    .icon-span {
      padding: 0 5px;
      height: 40px;
      line-height: 40px;
      font-size: 20px;
      color: #606266;
      display: inline-block;
      // vertical-align: top;
      // display: inline-block;
    }
    .label {
      height: 40px;
      line-height: 40px;
    }
    .tuan {
      &.chu {
        width: 60px;
        height: 40px;
        display: inline-block;
        span {
          width: 60px;
          display: inline-block;
          line-height: 20px;
          text-align: center;
          font-size: 12px;
          height: 20px;
          &:last-child {
            border-top: 1px solid #606266;
          }
        }
      }
      &.cheng {
        .name {
          height: 40px;
          line-height: 40px;
        }
        .icon-span {
          line-height: 40px;
          font-size: 16px;
          padding: 0 1px;
        }
      }
    }
  }
}
</style>
