<!--
 * @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" placeholder='点击选择店铺'>
              <template #append>
                <div @click="handleChooseShop">选择</div>
              </template>
            </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 key="dialog-footer">
        <el-button type="primary" @click="handleAddClick(formRef)">添加</el-button>
        <el-button @click="handleResetClick(formRef)">重置</el-button>
      </div>
    </template>
  </el-dialog>

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


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

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

  await getcharging_methods()

}



// -业务参数
const userid = useUserStore().userId
// 计费方式字典选项列表
const charging_methods = ref([]);
// 选择店铺弹窗参数
const ChooseShopDialogVisible = ref(false);
const ChooseShopDialogRow = ref({});
// 选择配送区域弹窗参数
const DeliveryRuleDialogVisible = ref(false);
const DeliveryRuleDialogRow = ref({});

// 配送区域和运费参数
const deliveryRuleFirstTitle = ref("首件 (个)")
const deliveryRuleAdditionalTitle = ref("续件 (个)")
const deliveryRuleDataList = ref([
  // {
  //   deliveryRuleRegionText: '北京 天津 河北省 山西省 内蒙古自治区 辽宁省 吉林省 黑龙江省 上海 江苏省 浙江省 安徽省 福建省 江西省 山东省 河南省 湖北省 湖南省 广东省 广西壮族自治区 海南省 重庆 四川省 贵州省 云南省 陕西省 甘肃省 青海省 宁夏回族自治区',
  //   deliveryRuleFirst: 1,
  //   deliveryRuleFirstFee: 0,
  //   deliveryRuleAdditional: 0,
  //   deliveryRuleAdditionalFee: 0
  // },
])



// -业务方法

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

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


// 打开选择店铺弹窗
const handleChooseShop = () => {
  ChooseShopDialogVisible.value = true
  ChooseShopDialogRow.value = formData
}

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


// 选择配送区域(回调)
const handleAddRegionRule = () => {
  let deliveryRuleRegionText = formData.deliveryRuleRegionText
  let deliveryRuleRegion = formData.deliveryRuleRegion
  // console.log(formData,'添加表单');
  let deliveryRuleData = {
    deliveryRuleRegionText: deliveryRuleRegionText,
    deliveryRuleRegion: deliveryRuleRegion,
    deliveryRuleFirst: 1,
    deliveryRuleFirstFee: 0,
    deliveryRuleAdditional: 0,
    deliveryRuleAdditionalFee: 0
  }
  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 labelWidth = 100;
const formRef = ref();
const { proxy } = getCurrentInstance()
const emits = defineEmits(["update:modelValue"]);
const formData = reactive({
  deliveryBillingMethod: 1,
  deliverySort: 100,
  deliveryRuleRegion: []
});
const props = defineProps({
  modelValue: Boolean,
  done: Function,
});
const imgData = ref({
  fileDir: "Delivery"
})

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

// -基础方法

// 提交
const handleAddClick = async (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (!valid) {
      return;
    }

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

    deliveryRuleDataList.value.map((item) => {
      const transformedRegion = item.deliveryRuleRegion.map((regionItem) => regionItem.id);
      item.deliveryRuleRegion = transformedRegion.join(',');
    });

    formData.deliveryRuleDataList = deliveryRuleDataList.value
    // console.log(formData, '表单');

    const { code } = await addOrUpdateDelivery(formData);
    if (code == 200) {
      modal.msgSuccess('添加成功')
      closeDialog();
    }
  });
};
const closeDialog = () => {
  formData.shopName = ""
  formData.deliveryRuleRegionText = ""
  formData.deliveryRuleRegion = []
  formData.deliveryRuleDataList = []
  deliveryRuleDataList.value = []

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


<style>
.deliveryRuleEdit {
  display: flex;
  justify-content: right;
}
</style>