<template>
  <el-dialog
    custom-class="center-dialog"
    :title="title"
    top="0vh"
    :visible.sync="dialogFormVisible"
    @close="close"
  >
    <el-form ref="form" label-width="150px" :model="form" :rules="rules">
      <el-form-item :label="__('管理员账号')" prop="user_account">
        <el-input
          v-model="form.user_account"
          clearable
          :placeholder="__('管理员信息账号')"
          :readonly="isReadOnly"
          :style="{ width: '48%' }"
          disabled
        />
        <el-input
          v-model="form.user_password"
          clearable
          :placeholder="__('密码为空，则使用已经存在的用户，否则新创建。')"
          style="margin-left: 10px"
          :style="{ width: '48%' }"
        />
      </el-form-item>
      <el-form-item :label="__('店铺信息')" prop="store_name">
        <el-input
          v-model="form.store_name"
          clearable
          :placeholder="__('请输入店铺名称')"
          :style="{ width: '100%' }"
          disabled
        />
      </el-form-item>
      <el-form-item :label="__('店铺等级')" prop="store_grade_id">
        <el-select
          v-model.trim="form.store_grade_id"
          clearable
          :placeholder="__('店铺等级')"
          :style="{ width: '48%' }"
        >
          <el-option
            v-for="item in options"
            :key="item.store_grade_id"
            :label="item.store_grade_name"
            :value="item.store_grade_id"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="__('经营品类')">
        <el-cascader
            v-model="cascaderValue"
            :options="cascaderOptions"
            placeholder="请选择经营品类"
            :show-all-levels="false"
            @change="handleChangeBizCategory"
            clearable
            :disabled="isReadOnly"
          />
      </el-form-item>
      <el-form-item :label="__('分账比例')" prop="split_ratio">
      <el-input v-model.trim="form.split_ratio"  :placeholder="__('比例在70%-99%之间')" clearable />
      </el-form-item>
      <el-form-item :label="__('所属分站')" prop="subsite_id">
        <el-select
          v-model.trim="form.subsite_id"
          clearable
          :placeholder="__('所属分站')"
          :style="{ width: '48%' }"
        >
          <el-option
            v-for="item in siteOptions"
            :key="item.subsite_id"
            :label="item.subsite_name"
            :value="item.subsite_id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否自营" prop="store_is_selfsupport">
        <el-radio-group v-model="form.store_is_selfsupport" size="medium">
          <el-radio
            v-for="(item, index) in store_is_selfsupportOptions"
            :key="index"
            :disabled="item.disabled"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否零售" prop="store_type">
        <el-radio-group v-model="form.store_type" size="medium">
          <el-radio
            v-for="(item, index) in store_typeOptions"
            :key="index"
            :disabled="item.disabled"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="线上线下" prop="store_o2o_flag">
        <el-radio-group v-model="form.store_o2o_flag" size="medium">
          <el-radio
            v-for="(item, index) in store_o2o_flagOptions"
            :key="index"
            :disabled="item.disabled"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="店铺内部运费(单位/分)" size="normal" prop="shopping_fee_inner" > 
      <div style="display: flex; align-items: center;">
        <el-input 
          v-model="form.shopping_fee_inner" 
          placeholder="请输入店铺内部运费"  
          clearable 
          style="width: 200px;"  
        />
        <el-tooltip 
          content="0-使用平台的内部运费；大于0使用店铺的内部运费"
          placement="top"  
          effect="dark"    
          style="margin-left: 8px;"  
        >
          <i class="el-icon-question" style="cursor: pointer; color: #909399; font-size: 14px;"></i>
        </el-tooltip>
      </div>
      </el-form-item>

      <el-form-item
        label="是否开启自配送"
        label-width="150px"
        prop="is_delivery_self"
      >
        <el-switch
          v-model="form.is_delivery_self"
          :active-value="1"
          :inactive-value="2"
          @change="handleDeliveryStatus"
          active-text="是"
          inactive-text="否"
        ></el-switch>
      </el-form-item>
      
      <el-form-item label="E签宝合同" prop="esign_contract_file_url">
        <template v-if="form.esign_contract_file_url">
          <el-button type="primary" size="small" @click="downloadContract" style="margin-right: 10px;">
            点击下载
          </el-button>
          <el-button type="warning" size="small" @click="resignContract">
            重新签署合同
          </el-button>
        </template>
        <template v-else>
          <el-button type="primary" size="small" @click="signContract">
            签署合同
          </el-button>
        </template>
      </el-form-item>
      <el-form-item
        v-if="false"
        :label="__('商户线下编号')"
        prop="store_o2o_merchant_id"
      >
        <el-input
          v-model="form.store_o2o_merchant_id"
          clearable
          :placeholder="__('请输入商户线下编号')"
          :style="{ width: '100%' }"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">{{ __('取消') }}</el-button>
      <el-button :loading="saveLoading" type="primary" @click="save">
        {{ __('确定') }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
// 商户-砍价
import { translateTitle as __ } from '@/utils/i18n'
import { doEdit, FindStoreLevel, storeSetUp } from '@/api/store/base'
import { GetStoreClassify } from '@/api/base/store/category'
import { getList as getSubsite,createByFile} from '@/api/plantform/subsite'
import {
  getStoreCategories
} from '@/api/shopAudit/shopAudit'
export default {
  name: 'StoreBaseEdit',

  data() {
    return {
      options: [],
      classifyData: [],
      siteOptions: [],
      cascaderValue: [],        // 级联选择器专用绑定值（数组类型）
      cascaderOptions: [],
      form: {
        store_is_open: 0,
        store_is_selfsupport: 1,
        store_type: 1,
        store_o2o_flag: 0,
        subsite_id: 0,
        split_ratio:0,
        esign_contract_file_url: '', // 合同文件链接
        store_id:''
      },
      rules: {
        user_password: [
          {
            required: true,
            message: '请输入店铺管理员密码',
            trigger: 'blur',
          },
        ],
        store_name: [
          {
            required: true,
            message: '请输入店铺名称',
            trigger: 'blur',
          },
        ],
        user_account: [
          {
            required: true,
            message: '请输入管理员账号',
            trigger: 'blur',
          },
        ],
        store_grade_id: [
          {
            required: true,
            message: '请选择店铺等级',
            trigger: 'change',
          },
        ],
        store_category_id: [
          {
            required: true,
            message: '请选择经营分类',
            trigger: 'change',
          },
        ],
        store_is_selfsupport: [
          {
            required: true,
            message: '不能为空',
            trigger: 'change',
          },
        ],
        store_type: [
          {
            required: true,
            message: '不能为空',
            trigger: 'change',
          },
        ],
        store_o2o_flag: [
          {
            required: true,
            message: '不能为空',
            trigger: 'change',
          },
        ],
        subsite_id: [
          {
            required: true,
            message: '请选择所属分站',
            trigger: 'change',
          },
        ],
      },
      store_is_selfsupportOptions: [
        {
          label: this.__('平台自营'),
          value: 1,
        },
        {
          label: this.__('加盟商家'),
          value: 0,
        },
      ],
      store_typeOptions: [
        {
          label: this.__('零售店铺'),
          value: 1,
        },
        {
          label: this.__('供应商店铺'),
          value: 2,
        },
      ],
      store_o2o_flagOptions: [
        {
          label: this.__('线上店铺'),
          value: 0,
        },
        {
          label: this.__('线下门店'),
          value: 1,
        },
      ],
      title: '',
      dialogFormVisible: false,
      saveLoading: false,
    }
  },
  computed: {
    isReadOnly() {
      return this.form.store_id !== undefined
    },
  },
  created() {
    this.fetchdataFindStoreLevel()
    this.fetchdataGetStoreClassify()
    this.getSubsiteList()
  },
  methods: {
    __,
    async fetchdataFindStoreLevel() {
      await FindStoreLevel().then((res) => {
        this.options = res.data
      })
    },
    async fetchdataGetStoreClassify() {
      try {
        const res = await getStoreCategories();
        if (res.status === 200 && res.data) {
          this.classifyData = res.data;
          // 关键：将分类数据格式化为级联选择器需要的结构
          this.cascaderOptions = this.transformStoreCategories(res.data);
          console.log("级联分类数据源：", this.cascaderOptions);
        } else {
          this.$baseMessage("获取经营品类失败", "error");
        }
      } catch (err) {
        this.$baseMessage("获取经营品类异常", "error");
        console.error(err);
      }
    },
    async getSubsiteList() {
      let param = {
        pageNum: 1,
        pageSize: 9999,
      }
      const { data } = await getSubsite(param)
      if (data) {
        this.siteOptions = data.items
      } else {
        this.siteOptions = []
      }
    },
    showEdit(row) {
      this.cascaderValue = [];
      if (!row) {
        // 新增：清空表单，设置标题
        this.title = this.__('新增');
        this.form = {
          store_is_open: 0,
          store_is_selfsupport: 1,
          store_type: 1,
          store_o2o_flag: 0,
          subsite_id: 0,
          split_ratio: 0,
          store_category_id: 0,
          store_2nd_category_id:0,
        };
      } else {
        this.title = this.__('编辑');
        this.form = Object.assign({}, row);
        if (row.store_category_id && row.store_2nd_category_id) {
          this.cascaderValue = [
            row.store_category_id,       // 一级分类ID
            row.store_2nd_category_id // 二级分类ID
          ];
        }
      }
      this.dialogFormVisible = true;
    },
    downloadContract() {
      if (!this.form.esign_contract_file_url) return;
      // 直接打开新窗口下载
      window.open(this.form.esign_contract_file_url, '_blank');
    },

    // 首次签署
    async signContract() {
      if (!this.form.store_id) {
        this.$message.warning('请先保存店铺基本信息，再签署合同');
        return;
      }
      try {
        const res = await createByFile({ store_id: this.form.store_id });
        if (res.status === 200 && res.data) {
          window.open(res.data.url, '_blank');
          // this.$emit('fetch-data');
        } else {
          this.$message.error(res.msg || '签署失败');
        }
      } catch (e) {
        this.$message.error('签署接口异常');
      }
    },

    // 重新签署
    async resignContract() {
      // 逻辑和首次签署基本一样，也可以调同一个接口
      await this.signContract();
    },
    close() {
      this.form = {
        store_is_selfsupport: 1,
        store_type: 1,
        store_o2o_flag: 0,
        store_is_open: 0,
      }
      this.$refs['form'].resetFields()
      this.dialogFormVisible = false
    },
    transformStoreCategories(data) {
      return data.map(item => ({
        value: item.store_category_id,
        label: item.store_category_name,
        children: item.children ? [
          // 添加一个与一级目录同名的选项
          {
            value: item.store_category_id,
            label: item.store_category_name
          },
          ...item.children.map(child => ({
              value: child.store_category_id,
              label: child.store_category_name
            }))
        ] : []
      }));
    },
    handleDeliveryStatus(e){
      this.form.is_delivery_self = e;
      console.log("D",e)
    },
    handleChangeBizCategory(value) {
      if (value && value.length === 2) {
        const [bizCategoryId, bizSecondCategoryId] = value;
        this.form.store_category_id = bizCategoryId; 
        this.form.store_2nd_category_id = bizSecondCategoryId; 
      }
    },
    save() {
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          if (this.form.store_id == undefined) {
            this.saveLoading = true
            const { msg, status } = await doEdit(this.form)
            this.saveLoading = false
            if (200 == status) {
              this.$baseMessage(msg, 'success')
            } else {
              this.$baseMessage(msg, 'error')
            }
            this.$emit('fetch-data')
          } else {
            this.saveLoading = true
            const { msg, status } = await storeSetUp(this.form)
            this.saveLoading = false
            if (200 == status) {
              this.$baseMessage(msg, 'success')
            } else {
              this.$baseMessage(msg, 'error')
            }
            this.$emit('fetch-data')
          }
          this.close()
        }
      })
    },
  },
}
</script>
