<!--
 * @Descripttion: (配送模板/tb_delivery 编辑弹窗)
 * @version: (1.0)
 * @Author: (lwh)
 * @Date: (2023-06-16)
 * @LastEditors: (lwh)
 * @LastEditTime: (2023-06-16)
-->
<template>
  <el-dialog v-model="props.modelValue" title="修改配送模板信息" width="1250px" @closed="closeDialog" @open="openDialog">
    <el-form ref="formRef" :model="formData" :rules="rules">


      <el-row>
        <el-col v-if="userid == 1" :lg="12">
          <el-form-item :label-width="labelWidth" label="店铺" prop="shopGuid">
            <el-input v-model='formData.shopName' disabled type="text">
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :lg="12">
          <el-form-item :label-width="labelWidth" label="模板名称" prop="deliveryName">
            <el-input v-model="formData.deliveryName" placeholder="请输入模板名称" />
          </el-form-item>
        </el-col>
        <el-col :lg="24">
          <el-form-item :label-width="labelWidth" label="计费方式" prop="deliveryBillingMethod">
            <el-radio-group v-model="formData.deliveryBillingMethod">
              <el-radio v-for="item in  charging_methods " :key="item.dictValue" :label="parseInt(item.dictValue)"
                @change="onChangeType">{{
                  item.dictLabel }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :lg="24">
          <el-form-item :label-width="labelWidth + 20" label="配送区域及运费" prop="">
            <el-table :data="deliveryRuleDataList" border style="width: 100%">
              <el-table-column prop="deliveryRuleRegionText" label="可配送区域" width="350">
                <template #default="scope">
                  <el-row style="width: 100%">
                    <el-col :span="24">
                      <div class="mr-5">{{ scope.row.deliveryRuleRegionText }}</div>
                    </el-col>
                  </el-row>
                  <el-row class="deliveryRuleEdit">
                    <el-link type="primary" style="margin-right: 10px;"
                      @click="handleDeliveryRuleEdit(scope.row)">编辑</el-link>
                    <el-link type="primary" @click="handleDeliveryRuleDelete(scope.row)">删除</el-link>
                  </el-row>
                </template>
              </el-table-column>
              <el-table-column prop="deliveryRuleFirst" :label=deliveryRuleFirstTitle>
                <template #default="scope">
                  <el-input-number v-if="formData.deliveryBillingMethod == 1" v-model.number="scope.row.deliveryRuleFirst"
                    controls-position="right" :min="0" />
                  <el-input-number v-else v-model.number="scope.row.deliveryRuleFirst" controls-position="right" :min="0"
                    :precision="2" />
                </template>
              </el-table-column>
              <el-table-column prop="deliveryRuleFirstFee" label="	运费(元)">
                <template #default="scope">
                  <el-input-number v-model.number="scope.row.deliveryRuleFirstFee" controls-position="right" :min="0"
                    :precision="2" />
                </template>
              </el-table-column>
              <el-table-column prop="deliveryRuleAdditional" :label=deliveryRuleAdditionalTitle>
                <template #default="scope">
                  <el-input-number v-if="formData.deliveryBillingMethod == 1"
                    v-model.number="scope.row.deliveryRuleAdditional" controls-position="right" :min="0" />
                  <el-input-number v-else v-model.number="scope.row.deliveryRuleAdditional" controls-position="right"
                    :min="0" :precision="2" />
                </template>
              </el-table-column>
              <el-table-column prop="deliveryRuleAdditionalFee" label="续费(元)">
                <template #default="scope">
                  <el-input-number v-model.number="scope.row.deliveryRuleAdditionalFee" controls-position="right" :min="0"
                    :precision="2" />
                </template>
              </el-table-column>
            </el-table>
            <el-button style="margin-top: 10px;" plain icon="Location"
              @click="hanldeDeliveryRule()">点击添加配送区域及运费</el-button>
          </el-form-item>
        </el-col>

        <el-col :lg="12">
          <el-form-item :label-width="labelWidth" label="排序" prop="deliverySort">
            <el-input-number v-model.number="formData.deliverySort" controls-position="right" :min="0" />
          </el-form-item>
        </el-col>

      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleEditClick(formRef)">编辑</el-button>
        <el-button @click="handleResetClick(formRef)">重置</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 选择配送区域及运费 -->
  <RegionTranser v-model="DeliveryRuleDialogVisible" :data="DeliveryRuleDialogRow" :done="handleAddRegionRule">
  </RegionTranser>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { ElMessageBox } from 'element-plus'
import modal from '@/plugins/modal.js'
import { reactive, ref, watch } from "vue";
import useUserStore from '@/store/modules/user'
import { getDeliveryRuleList, addOrUpdateDelivery } from "@/api/business/LogisticsManage/Deliverys/delivery.js";
import RegionTranser from './RegionTranser.vue';


// 打开弹窗时回调
const openDialog = async () => {
  await getcharging_methods()
  await getdeliveryRuleDataListFun()
}

const formData = ref({
  ...props.data,
});
watch(props, async (v) => {
  formData.value = v.data;
});

// 业务参数

const userid = useUserStore().userId
// 计费方式字典选项列表
const charging_methods = ref([]);

// 选择配送区域弹窗参数
const DeliveryRuleDialogVisible = ref(false);
const DeliveryRuleDialogRow = ref({});

// 配送区域和运费参数
const deliveryRuleFirstTitle = ref("首件 (个)")
const deliveryRuleAdditionalTitle = ref("续件 (个)")
const deliveryRuleDataList = ref([])



// -业务方法
//字典获取
async function getcharging_methods() {
  await proxy.getDicts('charging_methods').then((res) => {
    charging_methods.value = res.data
  })
}

// 获取配送模板的配送区域和运费列表
async function getdeliveryRuleDataListFun() {
  getDeliveryRuleList({ deliveryGuid: formData.value.deliveryGuid }).then((res) => {
    if (res.code == 200) {
      deliveryRuleDataList.value = res.data
      deliveryRuleDataList.value.map((item) => {
        item.deliveryRuleRegion = item.deliveryRuleRegion == null ? [] : item.deliveryRuleRegion
      })
    }
  })
}

// 选择计费方式
const onChangeType = (e) => {
  if (e === 1) {
    deliveryRuleFirstTitle.value = "首件 (个)"
    deliveryRuleAdditionalTitle.value = "续件 (个)"
  }
  if (e === 2) {
    deliveryRuleFirstTitle.value = "首重 (Kg)"
    deliveryRuleAdditionalTitle.value = "续重 (Kg)"
  }
}

// 打开选择配送区域弹窗
const hanldeDeliveryRule = () => {
  formData.value.deliveryRuleRegion = []
  DeliveryRuleDialogVisible.value = true
  DeliveryRuleDialogRow.value = formData.value
}


// 选择配送区域(回调)
const handleAddRegionRule = () => {
  let deliveryRuleRegionText = formData.value.deliveryRuleRegionText
  let deliveryRuleRegion = formData.value.deliveryRuleRegion
  let deliveryRuleData = {
    deliveryRuleRegionText: deliveryRuleRegionText,
    deliveryRuleRegion: deliveryRuleRegion,
    deliveryRuleFirst: 1,
    deliveryRuleFirstFee: 0,
    deliveryRuleAdditional: 0,
    deliveryRuleAdditionalFee: 0,
    deliveryGuid: ""
  }
  deliveryRuleDataList.value.push(deliveryRuleData)
}

// 编辑配送区域及运费
const handleDeliveryRuleEdit = (row) => {
  DeliveryRuleDialogVisible.value = true
  DeliveryRuleDialogRow.value = row
}

// 删除配送区域及运费
const handleDeliveryRuleDelete = (row) => {
  ElMessageBox.confirm("是否确认删除？", "系统提示", {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: "warning",
  })
    .then(() => {
      const index = deliveryRuleDataList.value.indexOf(row);
      if (index !== -1) {
        deliveryRuleDataList.value.splice(index, 1);
      }
      modal.msgSuccess("删除成功")
    })
    .catch(() => { })
}



// -基础参数
const props = defineProps({
  modelValue: Boolean,
  data: Object,
  done: Function,
});

const labelWidth = 100;
const formRef = ref();
const { proxy } = getCurrentInstance()
const emits = defineEmits(["update:modelValue"]);
const imgData = ref({
  fileDir: "Delivery"
})

// 验证
const rules = reactive({
  deliveryName: [{ required: true, message: "模板名称不能为空", trigger: "blur" }],
  deliveryBillingMethod: [{ required: true, message: "计费方式不能为空", trigger: "blur", type: "number" }],
  deliverySort: [{ required: true, message: "排序不能为空", trigger: "blur", type: "number" }],
});

// -基础方法
// 提交
const handleEditClick = async (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (!valid) {
      return;
    }

    if (deliveryRuleDataList.value.length <= 0) {
      modal.msgError("请添加配送区域及运费")
      return
    }

    deliveryRuleDataList.value.map((item) => {
      console.log(item.deliveryRuleRegion,'asda');
      if (item.deliveryRuleRegion == null) {
        return
      }
      const transformedRegion = item.deliveryRuleRegion.map((regionItem) => regionItem.id);
      item.deliveryRuleRegion = transformedRegion.join(',');
      item.deliveryGuid = formData.value.deliveryGuid
    });

    formData.value.deliveryRuleDataList = deliveryRuleDataList.value

    const { code } = await addOrUpdateDelivery(formData.value);
    if (code == 200) {
      modal.msgSuccess('修改成功')
      closeDialog();
    }
  });
}

const handleResetClick = async (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
}
const closeDialog = () => {
  props.done();
  emits("update:modelValue", false);
};

</script>
