<template>
  <div>
    <el-form ref="formRef" :model="editCacheData" :rules="rules">
      <el-table border size="mini" :data="list" max-height="300px">
        <el-table-column label="收货总数" prop="receipt_quantity">
          <template slot-scope="scope">
            <el-form-item v-if="scope.$index === editIndex" prop="receipt_quantity">
              <el-input size="mini" placeholder="收货总数" v-model="editCacheData.receipt_quantity" />
            </el-form-item>
            <span v-else>{{ scope.row.receipt_quantity }}</span>
          </template>
        </el-table-column>

        <el-table-column label="收货联系人">
          <template slot-scope="scope">
            <el-form-item v-if="scope.$index === editIndex" prop="contactor">
              <el-input size="mini" placeholder="收货联系人" v-model="editCacheData.contactor" />
            </el-form-item>
            <span v-else>{{ scope.row.contactor }}</span>
          </template>
        </el-table-column>

        <el-table-column label="收货联系电话" prop="mobile">
          <template slot-scope="scope">
            <el-form-item v-if="scope.$index === editIndex" prop="mobile">
              <el-input size="mini" placeholder="收货联系电话" maxlength="11" v-model="editCacheData.mobile" />
            </el-form-item>
            <span v-else>{{ scope.row.mobile }}</span>
          </template>
        </el-table-column>

        <el-table-column label="收货省市区" prop="addr_code">
          <template slot-scope="scope">
            <el-form-item v-if="scope.$index === editIndex" prop="addr_code">
              <select-area :value="editCacheData.addr_code" :placeholder="'收货省市区'" size="mini"
                @selectChange="handleInAddrChange($event)" />
            </el-form-item>
            <span v-else>{{ scope.row.addr_code_name }}</span>
          </template>
        </el-table-column>

        <el-table-column label="详细地址" prop="addr">
          <template slot-scope="scope">
            <el-form-item v-if="scope.$index === editIndex" prop="addr">
              <el-input size="mini" placeholder="详细地址" v-model="editCacheData.addr" />
            </el-form-item>
            <span v-else>{{ scope.row.addr }}</span>
          </template>
        </el-table-column>

        <el-table-column width="90px">
          <template #header>
            <el-tooltip placement="top" content="下载收货模板">
              <el-button size="mini" type="text" icon="el-icon-download" @click="downloadTemplate" />
            </el-tooltip>

            <el-tooltip placement="top" content="导入收货地址">
              <el-button size="mini" type="text" icon="el-icon-upload2" @click="handleShowModal" />
            </el-tooltip>

            <el-tooltip placement="top" content="手动添加地址">
              <el-button size="mini" type="text" icon="el-icon-circle-plus-outline" @click="handlePushAddress" />
            </el-tooltip>
          </template>

          <template slot-scope="scope">
            <el-button size="mini" v-if="Number(editIndex) === Number(scope.$index)" type="text" icon="el-icon-circle-check"
              @click="handleSave()" />
            <el-button v-else size="mini" type="text" icon="el-icon-edit" @click="handleSetEdit(scope.$index)" />
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.$index)" />
          </template>
        </el-table-column>
      </el-table>


      <el-form-item>
        <div style="width:100%;display:flex;justify-content:flex-end;margin-top:10px">
          <el-button type="primary" size="mini" @click="handleSubmit">保存</el-button>
        </div>
      </el-form-item>
    </el-form>


    <in-address-modal :show-model.sync="showModal" :loading="false" @refresh="handleRefresh" />
  </div>
</template>


<script>
import InAddressModal from "@/components/in-address-modal"
import { addressRules } from "./../config/rules"
import { utils, writeFile } from "xlsx";
import asyncRequest from "@/apis/report";

const defaultAddressData = {
  receipt_quantity: '',
  addr_code_name: '',
  contactor: '',
  addr_code: '',
  mobile: '',
  addr: ''
}

export default {
  props: ['id','num'],
  data() {
    return {
      list: [],
      editIndex: -1,
      loading: false,
      showModal: false,
      rules: addressRules,
      editCacheData: { ...defaultAddressData }
    }
  },
  components: {
    InAddressModal
  },
  methods: {
    handleShowModal() {
      this.showModal = true;
    },

    handleSetEdit(index) {
      if (this.editIndex >= 0) {
        this.$message.warning('当前已有地址在编辑，请保存后再试！');
        return;
      }
      this.editIndex = index;

      const { contactor, receipt_quantity, mobile, addr_code, addr, addr_code_name } = this.list[index];

      this.editCacheData = {
        contactor, receipt_quantity, mobile, addr_code, addr, addr_code_name
      }
    },

    downloadTemplate() {
      const data = Array(20).fill(0).map(() => ({
        '收货总数': '1',
        '收货联系人': '张三',
        '收货联系电话': '17878787878',
        '收货省名称': '北京市',
        '收货市名称': '北京市',
        '收货区名称': '东城区',
        '详细地址': 'xxx街道xxx号',
      }))

      const workBook = utils.book_new();
      const workSheet = utils.json_to_sheet(data);
      utils.book_append_sheet(workBook, workSheet, "sheet");

      //导出模板
      writeFile(workBook, "收货模板.xlsx", {
        bookType: "xlsx"
      });
    },
    handleDelete(index) {
      this.list.splice(index, 1)
      if (this.editIndex >= 0) this.editIndex = -1;
    },

    handleSave() {
      this.$refs.formRef.validate(async isValid => {
        if (!isValid) return;

        const { addr_code } = this.editCacheData;
        const { data, code } = await asyncRequest.addrall({ code: addr_code[addr_code.length - 1] })

        if (Number(code) === 0) {
          this.editCacheData.addr_code_name = data.province.name + '/' + data.city.name + '/' + data.area.name
        }

        this.$set(this.list, this.editIndex, this.editCacheData)
        this.editCacheData = { ...defaultAddressData }
        this.editIndex = -1;
      })
    },

    handleRefresh(data) {
      const _data = data.list.map(({ addr, addr_code, contactor, mobile, receipt_quantity, addr_code_name }) => ({
        addr,
        addr_code,
        contactor, mobile,
        receipt_quantity,
        addr_code_name
      }))

      this.list = [...this.list, ..._data]
      this.showModal = false;
    },

    handlePushAddress() {
      if (this.editIndex >= 0) {
        this.$message.warning('当前已有地址在编辑，请保存后再试！');
        return;
      }

      this.list.push({ ...defaultAddressData })
      this.editIndex = this.list.length - 1;
    },

    handleInAddrChange(e) {
      this.editCacheData['addr_code'] = e;
    },

    async handleSubmit() {
      if (this.editIndex !== -1) {
        this.$message.warning('当前已有地址在编辑，请保存后再试！')
        return
      }

      if(this.list.length === 0){
        this.$message.warning('至少填写一条记录！')
        return
      }

      const currentNum = this.list.reduce((current,prev) => {
        return Number(current) + Number(prev.receipt_quantity)
      },0)

      if(Number(this.num) > currentNum){
        this.$message.warning('收货数量小于销售数量！');
        return;
      }

      const { data, code, message } = await asyncRequest.transfer({
        id: this.id,
        addr_list: this.list
      });

      if (Number(code) === 0) {
        this.$emit("refresh");
      } else {
        this.$message.error(message)
      }
    }
  }
}
</script>
