<template>
  <ContainerTit>
    <div slot="headr">
      <el-button type="primary" :loading="sub_loading" @click="submitData">
        保存
      </el-button>
    </div>
    <div class="page-div">
      <el-form
        ref="delivery_form"
        class="d-tem-form"
        style="margin-top: 20px"
        :model="delivery_form"
        label-width="170px"
        :rules="form_rules"
        size="small"
      >
        <el-form-item label="模板名称：" prop="name">
          <el-input
            v-model="delivery_form.name"
            style="width: 280px"
            placeholder="请输入模版名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="计费方式：" prop="type">
          <el-radio-group v-model="delivery_form.type">
            <el-radio :label="4">计件</el-radio>
            <el-radio :label="5">计重</el-radio>
          </el-radio-group>
          <p class="form-tip">保存后计费方式不能更改</p>
        </el-form-item>
        <el-form-item label="配送区域：" prop="areas">
          <div style="border: 1px solid #eeeeee; border-bottom: 0">
            <el-table :data="delivery_form.areas">
              <el-table-column
                prop="text"
                label="配送区域"
                min-width="380"
              ></el-table-column>
              <el-table-column
                prop="firstNum"
                :label="`首件 (${delivery_form.type === 4 ? '个' : 'g'})`"
                min-width="140"
              >
                <template slot-scope="scope">
                  <el-input-number
                    v-model="scope.row.first_num"
                    style="width: 100%"
                    :controls="false"
                  ></el-input-number>
                </template>
              </el-table-column>
              <el-table-column
                prop="firstPrice"
                label="运费(元)"
                min-width="140"
              >
                <template slot-scope="scope">
                  <el-input-number
                    v-model="scope.row.first_price"
                    style="width: 100%"
                    :controls="false"
                  ></el-input-number>
                </template>
              </el-table-column>
              <el-table-column
                prop="addNum"
                :label="`续件 (${delivery_form.type === 4 ? '个' : 'g'})`"
                min-width="140"
              >
                <template slot-scope="scope">
                  <el-input-number
                    v-model="scope.row.second_num"
                    style="width: 100%"
                    :controls="false"
                  ></el-input-number>
                </template>
              </el-table-column>
              <el-table-column prop="addPrice" label="运费(元)" min-width="140">
                <template slot-scope="scope">
                  <el-input-number
                    v-model="scope.row.second_price"
                    style="width: 100%"
                    :controls="false"
                  ></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="操作" min-width="140" fixed="right">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    :disabled="scope.$index === 0"
                    @click="editArea(scope.row, scope.$index)"
                  >
                    编辑
                  </el-button>
                  <el-button
                    :disabled="scope.$index === 0"
                    type="text"
                    @click="delArea(scope.$index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div
            class="add-div"
            style="border-top: 0 none"
            @click="openAreaModel(2)"
          >
            <el-button size="small" type="text">
              <i class="el-icon-plus"></i>
              添加可配送区域和运费
            </el-button>
          </div>
          <p class="form-tip">
            根据件数来计算运费，当物品不足【首件数量】时，按照【首件费用】计算，超过部分按照【续件件数】和【续件费用】乘积来计算
          </p>
        </el-form-item>
        <el-form-item label="不配送区域：">
          <div class="add-div">
            <div v-if="delivery_form.not_dispatch_areas.text">
              <span style="margin-right: 10px">
                {{ delivery_form.not_dispatch_areas.text }}
              </span>
              <el-button size="small" type="text" @click="editNoRegion">
                编辑
              </el-button>
              <span>|</span>
              <el-button size="small" type="text" @click="delNoRegion">
                删除
              </el-button>
            </div>
            <el-button
              v-else
              size="small"
              type="text"
              @click="openAreaModel(1)"
            >
              <i class="el-icon-plus"></i>
              添加不配送区域
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <AreaSelect
      v-if="show_area"
      :default-region="default_region"
      :is-show="show_area"
      @cancel="cancelAreaModel"
      @confirm="selAreaConfirm"
    ></AreaSelect>
  </ContainerTit>
</template>

<script>
  import AreaSelect from "@/component/common/AreaSelect";
  import { getRuleInfo, setDataDelivery } from "@/api/System";
  export default {
    name: "AddDeliveryTem",
    components: { AreaSelect },
    data() {
      const checkAreas = (rule, value, callback) => {
        callback();
      };
      return {
        delivery_id: 0, // 配送方式ID
        rule_id: 0, // 运费模版ID
        region_index: "",
        default_region: [],
        show_area: false,
        form_rules: {
          name: [
            { required: true, message: "请输入模板名称", trigger: "blur" },
          ],
          type: [
            { required: true, message: "请选择计费方式", trigger: "change" },
          ],
          areas: [{ required: true, validator: checkAreas, trigger: "change" }],
        },
        is_can_region: 1, // 判断选择区域按钮点击，1是点击不配送按钮，2是点击配送按钮
        delivery_form: {
          name: "",
          type: 4,
          is_default: 4,
          areas: [
            {
              text: "全国统一运费",
              first_num: "",
              first_price: "",
              second_num: "",
              second_price: "",
              provinces: [],
              citys: [],
              areas: [],
            },
          ],
          not_dispatch_areas: {},
        },
      };
    },
    created() {
      // 配送方式ID
      this.delivery_id = this.$route.query.deiId;
      if (this.$route.query.id) {
        this.rule_id = this.$route.query.id;
        this.getRuleInfo();
      }
    },
    activated() {
      if (this.$_isInit()) return;
      // 配送方式ID
      this.delivery_id = this.$route.query.deiId;
      if (this.$route.query.id) {
        this.rule_id = this.$route.query.id;
        this.getRuleInfo();
      }
    },
    methods: {
      // 获取运费模版详情
      async getRuleInfo() {
        if (!this.$accessCheck(this.$Access.DeliverygetRuleInfo)) {
          return;
        }
        const { data } = await getRuleInfo(this.rule_id);
        const setData = data.setData;
        setData.areas.unshift({
          ...setData.uniform,
          text: "全国统一运费",
        });
        this.delivery_form = {
          name: setData.name,
          type: setData.type,
          delivery_form: setData.is_default,
          not_dispatch_areas: setData.not_dispatch_areas,
          areas: setData.areas,
        };
      },
      // 编辑区域
      editArea(row, index) {
        this.region_index = index;
        this.default_region = row.areaArr;
        this.openAreaModel(2);
      },
      // 删除区域
      delArea(index) {
        this.delivery_form.areas.splice(index, 1);
      },
      // 编辑不配送区域
      editNoRegion() {
        this.default_region = this.delivery_form.not_dispatch_areas.areaArr;
        this.openAreaModel(1);
      },
      // 删除不配送区域
      delNoRegion() {
        this.delivery_form.not_dispatch_areas = {};
      },
      // 打开选择区域弹窗
      openAreaModel(isCan) {
        this.is_can_region = isCan;
        this.show_area = true;
      },
      // 关闭选择区域弹窗
      cancelAreaModel() {
        this.region_index = "";
        this.default_region = [];
        this.show_area = false;
      },
      // 选择区域
      selAreaConfirm(regionList) {
        let provinces = [];
        let citys = [];
        let areas = [];

        let provincesT = [];
        let citysT = [];
        let areasT = {};

        /* ----------------省---------------- */
        regionList.forEach((item) => {
          provinces.push(item.value);
          if (item.isAll) {
            provincesT.push(item.label);
          }
          /* ---------------市----------------- */
          if (item.children && item.children.length) {
            item.children.forEach((itemC) => {
              citys.push(itemC.value);
              if (!item.isAll) {
                if (itemC.isAll) {
                  citysT.push(itemC.label);
                } else {
                  areasT[itemC.label] = [];
                }
              }

              /* --------------县区------------------ */
              if (itemC.children && itemC.children.length) {
                itemC.children.forEach((itemCC) => {
                  if (!itemC.isAll) {
                    areasT[itemC.label].push(itemCC.label);
                  }
                  areas.push(itemCC.value);
                });
              }
            });
          }
        });
        let discriptionT = [];
        for (let i in areasT) {
          discriptionT.push(i + "(" + areasT[i].join("、") + ")");
        }
        const text =
          provincesT.join("、") +
          (provincesT.length > 0 && citysT.length > 0 ? "、" : "") +
          citysT.join("、") +
          (discriptionT.length > 0 && citysT.length > 0
            ? "、"
            : discriptionT.length > 0 && citysT.length === 0
            ? "、"
            : "") +
          discriptionT.join("、");

        if (this.is_can_region === 2) {
          if (this.region_index !== "") {
            this.$set(this.delivery_form.areas, this.region_index, {
              ...this.delivery_form.areas[this.region_index],
              text: text,
              provinces: provinces,
              citys: citys,
              areas: areas,
              areaArr: regionList,
            });
          } else {
            this.delivery_form.areas.push({
              text: text,
              first_num: "",
              first_price: "",
              second_num: "",
              second_price: "",
              provinces: provinces,
              citys: citys,
              areas: areas,
              areaArr: regionList,
            });
          }
        } else {
          this.delivery_form.not_dispatch_areas = {
            text: text,
            provinces: provinces,
            citys: citys,
            areas: areas,
            areaArr: regionList,
          };
        }
        this.cancelAreaModel();
      },
      submitData() {
        this.$refs.delivery_form.validate(async (valid) => {
          if (valid) {
            const uniform = {
              first_num: this.delivery_form.areas[0].first_num,
              first_price: this.delivery_form.areas[0].first_price,
              second_num: this.delivery_form.areas[0].second_num,
              second_price: this.delivery_form.areas[0].second_price,
            };
            let areas = [];
            this.delivery_form.areas.forEach((item, index) => {
              if (index > 0) {
                areas.push(item);
              }
            });
            let params = {
              areas: areas,
              country: [],
              is_default: this.delivery_form.is_default,
              name: this.delivery_form.name,
              not_dispatch_areas: this.delivery_form.not_dispatch_areas,
              not_dispatch_country: {},
              type: this.delivery_form.type,
              uniform: uniform,
            };
            if (this.$route.name === "EditDeliveryTem") {
              params.id = this.rule_id;
            }
            this.sub_loading = true;
            try {
              const data = await setDataDelivery(this.delivery_id, params);
              this.sub_loading = false;
              if (!this.rule_id) {
                this.$message.success("新建成功");
              } else {
                this.$message.success("修改成功");
              }
              this.$closeCurrentGoEdit(
                "/SystemSettings/jiaoyiset/DeliveryTemplate/" + this.delivery_id
              );
            } finally {
              this.sub_loading = false;
            }
          }
        });
      },
    },
  };
</script>

<style></style>
<style scoped>
  .add-div {
    border: 1px solid #ebeef5;
    text-align: center;
    padding: 20px 0;
    cursor: pointer;
  }
</style>
