<template>
  <el-dialog
    v-loading="loading"
    :title="title"
    :center="true"
    align="left"
    top="5vh"
    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: -20px">
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form
            ref="ruleForm"
            :model="ruleForm"
            status-icon
            :rules="rulesThis"
            label-width="95px"
            class="demo-ruleForm"
          >
            <el-row>
              <el-col :span="12">
                <el-form-item label="商品分类" prop="goods_class">
                  search-sort 4444
                  <!-- <good-class
                    :value="ruleForm.goods_class"
                    @handleChange="goods_class_change"
                    :disabled="
                      !(
                        id === 'add' ||
                        (status === '0' && powers.some((i) => i == '005'))
                      )
                    "
                    :placeholder="'商品分类'"
                  /> -->
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="商品名称" prop="good_code">
                  <el-input
                    v-model="ruleForm.good_name"
                    readonly
                    maxlength="200"
                    @focus="hand"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="销售方" prop="sell_code">
                  <search-supplier
                    :type="'1'"
                    :size="searchSize"
                    :value="ruleForm.sell_code"
                    :disabled="false"
                    :is-detail="false"
                    @searchChange="supplierChange"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="购买方" prop="customer_code">
                  <search-customer
                    :value="ruleForm.customer_code"
                    @searchChange="customer_code_change"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <search-stock-good-modal
                  :once="true"
                  :cat_id="cat_id"
                  :show-model="showGoodsModel"
                  @cancel="showGoodsModel = false"
                  @searchChange="addGoodsRes"
                />
              </el-col>
            </el-row>
          </el-form>
        </el-col>
        <el-col :span="24" style="padding: 0 0 20px 0">
          <el-form ref="stockForm" :model="stockForm" :size="'mini'">
            <el-table
              :data="stockForm.good_stock"
              border
              :size="'mini'"
              style="width: 100%"
              row-key="key"
            >
              <el-table-column prop="wsm_supplierNo" label="发货公司编号" width="145" />

              <el-table-column
                show-overflow-tooltip
                prop="wsm_supplier"
                label="发货公司名称"
                min-width="145"
              />
              <el-table-column prop="wsm_code" label="发货仓库编码" width="180" />
              <el-table-column
                show-overflow-tooltip
                prop="wsm_name"
                label="发货仓库名称"
                min-width="180"
              />
              <el-table-column prop="usable_stock" label="商品可用库存" width="120" />

              <el-table-column prop="num" label="下单数量" width="150">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'good_stock.' + scope.$index + '.' + 'num'"
                    :rules="{}"
                    :size="'mini'"
                    style="margin-bottom: 0"
                  >
                    <el-input
                      v-model="scope.row.num"
                      maxlength="10"
                      :disabled="!scope.row.edit"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="original_price" label="销售价" width="110" />

              <el-table-column fixed="right" width="80" label="操作">
                <template slot-scope="scope">
                  <el-tooltip
                    v-if="!scope.row.edit"
                    effect="dark"
                    content="编辑"
                    placement="top"
                  >
                    <i class="el-icon-edit tb-icon" @click="editRow(scope.$index)" />
                  </el-tooltip>

                  <el-tooltip
                    v-if="scope.row.edit"
                    effect="dark"
                    content="保存"
                    placement="top"
                  >
                    <i
                      class="el-icon-circle-check tb-icon"
                      @click="checkStockRow(scope.$index)"
                    />
                  </el-tooltip>

                  <el-tooltip effect="dark" content="删除" placement="top">
                    <i
                      class="el-icon-delete tb-icon"
                      @click="deleteRow(scope.$index, stockForm.good_stock)"
                    />
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </el-col>
        <el-col :span="24" style="padding: 0 0 22px 0">
          <div style="height: 40px; margin: -10px 0 0 0" class="tr">
            <download-addr />
            <el-button
              type="primary"
              size="mini"
              style="margin: 0 0 0 10px"
              @click="addrmodel = true"
            >导入收货地址</el-button>
          </div>
          <el-form ref="addrForm" :model="addrForm" :size="'mini'">
            <el-table
              :data="addrForm.order_addr"
              border
              :size="'mini'"
              style="width: 100%"
              row-key="key"
            >
              <el-table-column prop="receipt_quantity" label="收货总数" min-width="125" />

              <el-table-column prop="arrive_time" label="最晚收货日期" width="150" />
              <el-table-column prop="contactor" label="收件联系人" min-width="110" />

              <el-table-column prop="mobile" label="收货联系电话" min-width="130" />

              <el-table-column prop="addr_code" label="收货省市区" min-width="230" />
              <el-table-column prop="addr" label="详细地址" min-width="170" />
              <el-table-column fixed="right" width="80">
                <template slot="header" slot-scope="scope">
                  <span>操作</span>
                  <el-tooltip
                    class="fr"
                    style="margin: 3px 0 0 0"
                    effect="dark"
                    content="添加"
                    placement="top"
                  >
                    <i
                      class="el-icon-circle-plus-outline tb-icon"
                      style="color: #6954f0"
                      @click="openHouseModal(-1)"
                    />
                  </el-tooltip>
                </template>
                <template slot-scope="scope">
                  <el-tooltip
                    v-if="!scope.row.edit"
                    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, addrForm.order_addr)"
                    />
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </el-col>

        <el-col :span="24">
          <in-addr-model
            :show-model="addrmodel"
            @cancel="addrmodel = false"
            @refresh="addrRefresh"
          />
          <addr-add-edit-modal
            :show-model="showAddrAddEditModal"
            :index="AddrAddEditModalIndex"
            :sitem="AddrAddEditModalSitem"
            @cancel="showAddrAddEditModal = false"
            @refresh="showAddrAddEditModalRefresh"
          />
        </el-col>
        <el-col :span="24" style="text-align: right">
          <el-button :size="'mini'" type="primary" @click="submitForm">保 存 </el-button>
        </el-col>
      </el-row>
    </el-card>
  </el-dialog>
</template>
<script>
import resToken from '@/mixins/resToken'
import asyncRequest from '@/apis/service/sellOut/salesOrder/detail'
import searchStockGoodModal from '@/components/search-stock-good-modal'
import {
  isnumber,
  isMobile,
  isChinese,
  isEmoticon,
  isSpecialSymbol,
  hasSpace,
  isAddr
} from '@/utils/validate'
import inAddrModel from '@/components/in-addr-model'
import AddrAddEditModal from '@/components/addr-add-edit-modal'
export default {
  name: 'Allot',
  components: { searchStockGoodModal, inAddrModel, AddrAddEditModal },
  mixins: [resToken],
  props: ['showModel', 'id'],
  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 {
          if (!isChinese(value)) {
            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: {},
      loading: false,
      addrmodel: false,
      title: '新建销售订单',
      showModelThis: this.showModel,
      showGoodsModel: false,
      stock_code: '',
      cat_id: '',
      ruleForm: {
        goods_class: [],
        good_name: '',
        good_code: '', // 商品选择
        customer_code: [], // 企业客户选择
        sell_code: [] // 销售方选择
      },
      rulesThis: this.rules,
      rules: {
        goods_class: [
          {
            type: 'array',
            required: true,
            message: '请选择商品分类',
            trigger: 'change'
          }
        ],
        good_code: [
          {
            required: true,
            message: '请选择商品',
            trigger: 'blur'
          }
        ],
        customer_code: [
          {
            type: 'array',
            required: true,
            message: '请选择企业客户',
            trigger: 'change'
          }
        ],
        sell_code: [
          {
            type: 'array',
            required: true,
            message: '请选择供应商公司',
            trigger: 'change'
          }
        ]
      },
      addrForm: {
        order_addr: [] // 收货地址
      },
      addrRules: {
        arrive_time: [
          {
            required: true,
            message: '最晚收货日期不能为空',
            trigger: 'change'
          }
        ],
        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: true,
            message: '收货省市区不能为空',
            trigger: 'change'
          }
        ],
        addr: [
          {
            required: true,
            validator: validateAddr,
            trigger: 'blur'
          }
        ]
      },
      stockForm: {
        good_stock: [] // 出货仓库
      },
      loading: false,
      id: ''
    }
  },
  watch: {
    showModel: function(val) {
      this.showModelThis = val
      if (val) {
        this.rulesThis = this.rules
        this.resetForm()
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit('cancel')
      }
    }
  },
  methods: {
    closeModel() {
      console.log('closeModel!!')
      this.showModelThis = false
    },
    hand() {
      if (this.ruleForm.goods_class.length === 0) {
        this.$message.warning('请选择商品分类！')
        return
      }
      this.showGoodsModel = true
    },
    addrRefresh(e) {
      const { list } = e
      this.addrForm.order_addr.push(...list)
    },

    goods_class_change(e) {
      this.ruleForm.goods_class = e
      this.cat_id = e.length > 0 ? e[e.length - 1] : ''
      this.$refs.ruleForm.validateField('goods_class')
      this.ruleForm.good_code = ''
      this.ruleForm.good_name = ''
      this.$refs.ruleForm.validateField('good_code')
    },
    refresh(e) {
      this.showModelThis = e
      this.$emit('refresh', true)
    },
    async getstock(code) {
      this.loading = true
      const model = {
        wsm_code: '',
        page: 1,
        size: 100,
        type_code: code,
        good_code: '',
        good_name: '',
        supplierNo: '',
        stock_low: '',
        stock_up: '',
        warn_low: '',
        warn_up: '',
        stock_max: '1'
      }
      const res = await asyncRequest.getGoodStock(model)
      if (res && res.code === 0 && res.data) {
        this.stockForm = {
          good_stock: [] // 出货仓库
        }
        const { list } = res.data
        list.forEach((v) => {
          const model = {
            num: v.usable_stock,
            usable_stock: v.usable_stock,
            wsm_name: v.wsm_name,
            wsm_supplier: v.wsm_supplier,
            wsm_supplierNo: v.wsm_supplierNo,
            wsm_code: v.wsm_code,
            original_price: v.original_price,
            edit: false
          }
          this.stockForm.good_stock.push(model)
        })
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout()
      } else {
        this.$message.warning(res.message)
      }
      this.loading = false
    },

    getNewTime() {
      this.newTime = new Date().valueOf()
    },
    async resetForm() {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields()
          this.$refs.ruleForm.clearValidate()
          this.cat_id = ''
          this.ruleForm = {
            goods_class: [],
            good_code: '', // 商品选择
            customer_code: [], // 企业客户选择
            sell_code: [] // 销售方公司
          }
        }
        if (this.$refs.stockForm) {
          this.$refs.stockForm.resetFields()
          this.$refs.stockForm.clearValidate()

          this.stockForm = {
            good_stock: [] // 出货仓库
          }
        }
        if (this.$refs.addrForm) {
          this.$refs.addrForm.resetFields()
          this.$refs.addrForm.clearValidate()
          this.addrForm = {
            order_addr: []
          }
        }
      })
    },
    showAddrAddEditModalRefresh(e) {
      const { index, item } = e

      if (index === -1) {
        this.addrForm.order_addr.push(JSON.parse(JSON.stringify(item)))
      } else {
        const {
          arrive_time,
          receipt_quantity,
          contactor,
          mobile,
          addr_code,
          addr_code_name,
          addr,
          id
        } = JSON.parse(JSON.stringify(item))
        this.addrForm.order_addr[index].receipt_quantity = receipt_quantity
        this.addrForm.order_addr[index].arrive_time = arrive_time
        this.addrForm.order_addr[index].contactor = contactor
        this.addrForm.order_addr[index].mobile = mobile
        this.addrForm.order_addr[index].addr_code = addr_code
        this.addrForm.order_addr[index].addr_code_name = addr_code_name
        this.addrForm.order_addr[index].addr = addr
        this.addrForm.order_addr[index].id = id
      }
      this.$refs.addrForm.validateField('addrlist')
    },
    async addGoodsRes(e) {
      if (e && e.length === 1) {
        this.ruleForm.good_name = e[0].good_name
        this.ruleForm.good_code = e[0].type_code
      } else {
        this.ruleForm.good_name = ''
        this.ruleForm.good_code = ''
      }
      this.$refs.ruleForm.validateField('good_code')
      if (this.ruleForm.good_code !== '' && this.id === 'add') {
        await this.getstock(this.ruleForm.good_code)
      } else {
        this.stockForm = {
          good_stock: [] // 出货仓库
        }
      }
    },
    editRow(index) {
      const findex = this.stockForm.good_stock.findIndex((v) => v.edit === true)
      if (findex !== -1) {
        this.$message.warning('当前已有发货仓库信息在编辑，请保存后再试！')
        return
      } else {
        this.stockForm.good_stock[index].edit = true
      }
    },
    checkStockRow(index) {
      const total = parseInt(this.stockForm.good_stock[index].usable_stock)
      const num = parseInt(this.stockForm.good_stock[index].num)
      if (total === 0) {
        this.$message.warning('该仓库已无该商品库存！不能销售！')
        return
      } else {
        if (num > total) {
          this.$message.warning('销售数量不能大于可用库存！')
          return
        } else {
          this.stockForm.good_stock[index].edit = false
        }
      }
    },
    customer_code_change(e) {
      if (e && e.code) {
        this.ruleForm.customer_code = [e.code]
      } else {
        this.ruleForm.customer_code = []
      }
      this.$refs.ruleForm.validateField('customer_code')
    },
    supplierChange(e) {
      if (e && e.id) {
        this.ruleForm.sell_code = [e.code]
        // this.wsm_supplierNo = [e.code];
      } else {
        this.ruleForm.sell_code = []
        // this.wsm_supplierNo = [];
      }
      // this.parmValue.wsm_code = "";
      // this.wsm_code = [];
      // this.parmValue.page = 1;
      // this.pageInfo.curr = 1;
      this.$refs.ruleForm.validateField('sell_code')
    },
    openHouseModal(index) {
      this.AddrAddEditModalIndex = index
      if (index === -1) {
        this.AddrAddEditModalSitem = {}
      } else {
        this.AddrAddEditModalSitem = JSON.parse(
          JSON.stringify(this.addrForm.order_addr[index])
        )
      }
      this.showAddrAddEditModal = true
      // let findex = this.addrForm.order_addr.findIndex((v) => v.edit === true);
      // if (findex !== -1) {
      //   this.$message.warning("当前已有地址在编辑，请保存后再试！");
      //   return;
      // } else {
      //   if (index === -1) {
      //     this.addrForm.order_addr.push({
      //       edit: true,
      //       arrive_time: "",
      //       receipt_quantity: "",
      //       contactor: "",
      //       mobile: "",
      //       addr_code: [],
      //       addr: "",
      //     });
      //   } else {
      //     this.addrForm.order_addr[index].edit = true;
      //   }
      // }
    },
    // 省市区选择
    select_area_change(e, index) {
      this.addrForm.order_addr[index].addr_code = e
    },
    // 省市区保存某一行
    checkRow(rowIndex) {
      this.$refs.addrForm.validate((valid) => {
        if (valid) {
          this.addrForm.order_addr[rowIndex].edit = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 省市区删除行操作
    deleteRow(index, rows) {
      rows.splice(index, 1)
    },
    async submitForm() {
      await this.$refs.ruleForm.validate(async(valid) => {
        if (valid) {
          if (this.loading) {
            return
          }
          this.loading = true
          const { good_code, customer_code, sell_code } = JSON.parse(
            JSON.stringify(this.ruleForm)
          )
          const { good_stock } = JSON.parse(JSON.stringify(this.stockForm))
          const { order_addr } = JSON.parse(JSON.stringify(this.addrForm))
          const model = {
            good_code,
            supplierNo: sell_code.join(','),
            customer_code: customer_code.join(','), // 账号
            order_addr: [],
            good_stock: []
          }
          let stockT = 0
          let addrT = 0
          let isStockOk = true
          let isSEdit = false
          let isAEdit = false
          good_stock.forEach((v1) => {
            if (v1.edit) {
              isSEdit = true
            }
            if (parseInt(v1.usable_stock) < parseInt(v1.num)) {
              isStockOk = false
            }
            stockT += parseInt(v1.num)
            const model1 = {
              num: v1.num,
              wsm_code: v1.wsm_code
            }
            model.good_stock.push(model1)
          })
          order_addr.forEach((v2) => {
            if (v2.edit) {
              isAEdit = true
            }
            addrT += parseInt(v2.receipt_quantity)
            const model2 = {
              contactor: v2.contactor,
              mobile: v2.mobile,
              arrive_time: v2.arrive_time,
              addr: v2.addr,
              receipt_quantity: v2.receipt_quantity,
              addr_code: v2.addr_code
            }
            model.order_addr.push(model2)
          })
          if (isSEdit) {
            this.$message.warning('请保存仓库信息！')
            this.loading = false
            return
          }
          if (isAEdit) {
            this.$message.warning('请保存地址信息！')
            this.loading = false
            return
          }
          if (!isStockOk) {
            this.$message.warning('部分仓库销售数量已大于可用数量！')
            this.loading = false
            return
          }
          if (stockT !== addrT) {
            this.$message.warning('库存出库总数量，与收货地址信息中的总数量不一致！')
            this.loading = false
            return
          }

          const res = await asyncRequest.add(model)

          this.loading = false
          if (res && res.code === 0) {
            this.$notify.success({
              title: '添加成功',
              message: ''
            })
            this.showModelThis = false
            // 刷新
            this.$emit('refresh')
          } else if (res && res.code >= 100 && res.code <= 104) {
            await this.logout()
          } else {
            this.$message.warning(res.message)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
// .capitalClaim {
.excelUploadBox {
  position: relative;
  width: 100%;
  height: 120px;
  line-height: 120px;
  box-sizing: border-box;
  &:hover {
    cursor: pointer;
  }
  .el-icon-receiving {
    width: 100%;
    text-align: center;
    height: 50px;
    display: block;
    font-size: 32px;
    line-height: 90px;
    color: #d3d4d6;
  }
  .boxM {
    width: 100%;
    display: block;
    text-align: center;
    line-height: 65px;
    height: 60px;
    color: #909399;
  }
}
.excelUpload {
  top: 0;
  left: 0;
  position: absolute;
  z-index: 2;
  width: 100%;
  height: 120px;
  line-height: 120px;
  box-sizing: border-box;
}
.excelUploadRes {
  width: 100%;
  height: 120px;
  line-height: 120px;
  box-sizing: border-box;
  i {
    width: 55px;
    height: 120px;
    line-height: 120px;
    text-align: center;
    font-size: 20px;
    &.fl {
      padding-left: 16px;
    }
    &.fr {
      padding-right: 16px;
      &:hover {
        cursor: pointer;
      }
    }
  }
  span {
    width: 386px;
    line-height: 16px;
    margin: 52px 0 0 0;
    font-size: 16px;
  }
}
// }
</style>
