<template>
  <div>
    <div style="display:flex;margin-bottom: 10px">
      <p style="width:80px">
        <span style="color:red">*</span>&nbsp;客户公司
      </p>
      <search-customer
        :value="ruleForm.companyCode"
        :names="ruleForm.companyName"
        :placeholder="'客户公司'"
        :size="'mini'"
        @searchChange="customerChange"
      />
    </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 v-model="editCacheData.receipt_quantity" size="mini" placeholder="收货总数" />
            </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 v-model="editCacheData.contactor" size="mini" placeholder="收货联系人" />
            </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
                v-model="editCacheData.mobile"
                size="mini"
                placeholder="收货联系电话"
                maxlength="11"
              />
            </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)"
              />-->
              <search-area
                :value="editCacheData.area_code"
                :is-detail="scope.$index === editIndex"
                :disabled="!scope.$index === editIndex"
                size="mini"
                :names="[getAddrName(scope.row.addr_code_name)]"
                placeholder="收货省市区"
                :level="3"
                @searchChange="areaChange($event,scope.$index)"
              />
            </el-form-item>
            <span v-else>{{getAddrName(scope.row.addr_code_name,true)}}</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 v-model="editCacheData.addr" size="mini" placeholder="详细地址" />
            </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
              v-if="Number(editIndex) === Number(scope.$index)"
              size="mini"
              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/service/sellOut/filing";

const defaultAddressData = {
  receipt_quantity: "",
  addr_code_name: "",
  contactor: "",
  addr_code: "",
  mobile: "",
  addr: "",
  area_code: "",
  area_label: ""
};

export default {
  components: { InAddressModal },
  props: ["id", "num"],
  data() {
    return {
      ruleForm: {
        companyName: "",
        companyCode: ""
      },
      list: [],
      editIndex: -1,
      loading: false,
      showModal: false,
      rules: addressRules,
      editCacheData: { ...defaultAddressData },
      companyName: ""
    };
  },
  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,
        area_code,
        area_label
      } = this.list[index];

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

    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;
    },
    getAddrName(name, modifider) {
      if (modifider) return name;
      const _n = name.split("/").join("");
      return _n;
    },

    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;
      });
    },

    customerChange(evt) {
      const { code, label } = evt;

      this.ruleForm = {
        companyCode: code ? [code] : "",
        companyName: label ? [label] : ""
      };
    },

    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,
          area_code: [addr_code[addr_code.length - 1]]
        })
      );

      console.log(_data);

      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;
    },

    async areaChange(e) {
      console.log(e);
      const { code, area_code, splitLabel } = e;
      this.editCacheData.area_label = splitLabel
        ? splitLabel.split(",").join("/")
        : "";

      this.editCacheData["area_code"] = area_code ? [area_code] : [];

      this.editCacheData["addr_code"] = code ? code.split(",") : [];
    },

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

    async handleSubmit() {
      if (!this.ruleForm.companyCode) {
        this.$message.warning("请选择客户公司");
        return;
      }

      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 (currentNum > Number(this.num)) {
        this.$message.warning(
          `未转单数量为${this.num},收货数量总和不能超过未转单数量！`
        );
        return;
      }

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

        customerCode: Array.isArray(this.ruleForm.companyCode)
          ? this.ruleForm.companyCode[0]
          : this.ruleForm.companyCode
      });

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