<template>
  <div class="app-container">
    <!-- 列表 -->
    <template v-if="isA">
      <!-- 搜索 -->
      <page-search ref="searchRef" :search-config="searchConfig" @query-click="handleQueryClick"
        @reset-click="handleResetClick" />

      <!-- 列表 -->
      <page-content ref="contentRef" :content-config="contentConfig" @add-click="handleAddClick"
        @edit-click="handleEditClick" @export-click="handleExportClick" @search-click="handleSearchClick"
        @toolbar-click="handleToolbarClick" @operat-click="handleOperatClick" @filter-change="handleFilterChange">
        <template #deptName="scope">
          <div style="display: inline-block;width: 50px;">
            {{ scope.row.name }}
          </div>
          <!-- <el-text></el-text> -->
        </template>
        <template #status="scope">
          <el-tag :type="scope.row[scope.prop] == 1 ? 'success' : 'info'">
            {{ scope.row[scope.prop] == 1 ? "启用" : "禁用" }}
          </el-tag>
        </template>
        <template #gender="scope">
          <DictLabel v-model="scope.row[scope.prop]" code="gender" />
        </template>
        <template #mobile="scope">
          <el-text>{{ scope.row[scope.prop] }}</el-text>
          <copy-button v-if="scope.row[scope.prop]" :text="scope.row[scope.prop]" style="margin-left: 2px" />
        </template>
        <template #operates="scope">
          <!-- <el-button type="text" size="small" v-if="scope.row.level < 3 && !isSyncStatus()"
            @click="addlowerLevel(scope.row)">添加下一级</el-button> -->
          <el-button type="primary" link size="small" v-if="!isSyncStatus() && scope.row.pid == 0"
            @click="handleEditClick(scope.row)">编辑</el-button>
          <el-button type="danger" link size="small" v-if="!isSyncStatus()"
            @click="deleteClick(scope.row)">删除</el-button>
        </template>
      </page-content>
      <!-- 添加下一级-编辑 -->
      <myDialog title="添加模板" width="50%" ref="myDialogRefs" @Confirm="subitgoods">
        <el-form ref="forms" :model="datas.contentForm" :rules="datas.rules" label-width="80px" label-position="left">
          <el-form-item label="规格名称" prop="name">
            <el-input v-model="datas.contentForm.name" placeholder="请输入下一级名称"></el-input>
          </el-form-item>
        </el-form>
      </myDialog>
      <!-- 新增 -->
      <!-- <page-modal ref="addModalRef" :modal-config="addModalConfig" @submit-click="handleSubmitClick">
        <template #gender="scope">
          <Dict v-model="scope.formData[scope.prop]" code="gender" />
        </template>
      </page-modal> -->
      <myDialog title="新增模板" width="70%" ref="myDialogRef" @Confirm="subitgood">
        <el-form ref="form" :model="datas.contentForm" :rules="datas.rules" label-width="80px" label-position="left">
          <el-form-item label="名称" prop="name">
            <el-input v-model="datas.contentForm.name" placeholder="模板名称，如：主食、酒水等"></el-input>
          </el-form-item>
          <el-form-item :label="item.name" v-for="(item, index) in datas.contentForm.children" :key="index">
            <div class="tag_wrap">
              <el-tag v-for="(val, i) in item.children" :key="i" closable size="medium" :disable-transitions="true"
                @close="handleClose(index, i)">
                {{ val.name }}
              </el-tag>
              <el-input class="input-new-tag" v-show="item.inputVisible" v-model="item.inputValue" ref="saveTagInput"
                size="small" placeholder="请输入规格值，回车添加" @keyup.enter.native="handleInputConfirm(index)"
                @blur="handleInputConfirm(index)">
              </el-input>
              <el-button v-show="!item.inputVisible" size="small" icon="Plus" plain @click="showInput(index)">
                添加
              </el-button>
              <el-button size="small" icon="Delete" plain @click="deleteTag(index)">删除</el-button>
            </div>
          </el-form-item>
        </el-form>
        <el-form ref="skuForm" :model="datas.skuForm" :rules="datas.skuRules" label-width="80px" label-position="left">
          <el-row :gutter="20" v-if="datas.showSkuForm">
            <el-col :span="10">
              <el-form-item label="规格" prop="skuValidate1">
                <el-input v-model="datas.skuForm.label" placeholder="规格，如：口味、温度等"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="规格值" prop="skuValidate2">
                <el-input v-model="datas.skuForm.value" placeholder="规格值，如：微辣、多辣、常温、冰等"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-button type="primary" @click="addSkuSubmit">添加</el-button>
              <el-button @click="datas.showSkuForm = false">取消</el-button>
            </el-col>
          </el-row>
          <el-form-item>
            <el-button type="primary" icon="Plus" @click="datas.showSkuForm = true">添加规格</el-button>
          </el-form-item>
        </el-form>
      </myDialog>
      <!-- 编辑 -->
      <page-modal ref="editModalRef" :modal-config="editModalConfig" @submit-click="handleSubmitClick">
        <template #gender="scope">
          <Dict v-model="scope.formData[scope.prop]" code="gender" v-bind="scope.attrs" />
        </template>
      </page-modal>
    </template>
    <template v-else>
      <page-content ref="contentRef" :content-config="contentConfig2" @operat-click="handleOperatClick">
        <template #status="scope">
          <el-tag :type="scope.row[scope.prop] == 1 ? 'success' : 'info'">
            {{ scope.row[scope.prop] == 1 ? "启用" : "禁用" }}
          </el-tag>
        </template>
      </page-content>
    </template>
  </div>
  <addSkuModal ref="addSkuModalRef" @success="handleResetClick" />
</template>

<script setup lang="ts">
import UserAPI from "@/api/product/specificationsconfig";
import RoleAPI from "@/api/system/role";
import type { IObject, IOperatData } from "@/components/CURD/types";
import usePage from "@/components/CURD/usePage";
import addModalConfig from "./specificationsconfig/add";
import contentConfig from "./specificationsconfig/content";
import contentConfig2 from "./specificationsconfig/content2";
import editModalConfig from "./specificationsconfig/edit";
import searchConfig from "./specificationsconfig/search";
import { pid } from "process";
import { isSyncStatus } from "@/utils/index";
import addSkuModal from "./components/addSkuModal.vue";

const addSkuModalRef = ref(null)

const validateSku1 = (rule, value, callback) => {
  if (!datas.skuForm.label) {
    callback(new Error(' '))
  } else {
    callback()
  }
}
const validateSku2 = (rule, value, callback) => {
  if (!datas.skuForm.value) {
    callback(new Error(' '))
  } else {
    callback()
  }
}
const {
  searchRef,
  contentRef,
  addModalRef,
  editModalRef,
  handleQueryClick,
  handleResetClick,
  // handleAddClick,
  // handleEditClick,
  handleSubmitClick,
  handleExportClick,
  handleSearchClick,
  handleFilterChange,
} = usePage();
// refs
const skuForm = ref(null)
const myDialogRefs = ref(null)
const forms = ref(null)

let datas = reactive({
  contentForm: {
    name: '',
    children: [],
  },
  skuForm: {
    label: '', value: ''
  },
  rules: {
    name: [
      {
        required: true,
        message: ' ',
        trigger: 'blur'
      }
    ]
  },

  skuRules: {
    skuValidate1: {
      required: true,
      validator: validateSku1,
      trigger: 'blur'
    },
    skuValidate2: {
      required: true,
      validator: validateSku2,
      trigger: 'blur'
    }
  },
  showSkuForm: false,
  addchilderinfo: {}
})
let myDialogRef = ref(null)
if (isSyncStatus()) {
  contentConfig.toolbar[0].hidden = true
} else {
  contentConfig.toolbar[0].hidden = false
}

function subitgood() {
  skuForm.value.validate(async valid => {
    if (valid) {
      let res = await UserAPI.quickAdd(datas.contentForm)
      if (res.code == 200) {
        ElMessage.success("添加成功");
        handleQueryClick();
        datas.contentForm.name = ''
        datas.contentForm.children = []
        myDialogRef.value?.close();

      }
    }
  })
}
function subitgoods() {
  forms.value.validate(async valid => {
    if (valid) {
      let obj = {
        name: datas.contentForm.name,
        level: datas.addchilderinfo.level < 3 ? (datas.addchilderinfo.level + 1) : 3,
        pid: datas.addchilderinfo.id
      }
      let res = await UserAPI.addunit(obj)
      if (res.code == 200) {
        ElMessage.success("添加成功");
        myDialogRefs.value.close()
        handleQueryClick();
        datas.contentForm.name = ''
      }
    }
  })
}
function handleClose(index: any, i: any) {
  console.log(datas.contentForm.children[index].children, 22222222)
  datas.contentForm.children[index].children.splice(i, 1);
}
function showInput(index: any) {
  datas.contentForm.children[index].inputVisible = true;
}
function addSkuSubmit() {
  skuForm.value.validate(async valid => {
    if (valid) {
      datas.contentForm.children.push({
        name: datas.skuForm.label,
        children: [{ name: datas.skuForm.value }],
        inputVisible: false,
        inputValue: ''
      })
      datas.skuForm.label = ''
      datas.skuForm.value = ''
      datas.showSkuForm = false
    }
  })
}
// 回车添加
function handleInputConfirm(index: number) {
  let inputValue = datas.contentForm.children[index].inputValue;
  if (inputValue) {
    datas.contentForm.children[index].children.push({ name: inputValue });
  }
  datas.contentForm.children[index].inputVisible = false;
  datas.contentForm.children[index].inputValue = '';
}
// 删除
// 删除已添加的规格
function deleteTag(index: number) {
  datas.contentForm.children.splice(index, 1);
}
// 添加下一级
async function addlowerLevel(item: any) {
  datas.addchilderinfo = item
  myDialogRefs.value.open()
  // addModalRef.value?.setModalVisible();
  // addModalConfig.formItems[2]!.attrs!.data = await UserAPI.getPage({ name: "" });
}
// function handleEditClicks(item: any) {
//   console.log(item)
// }
function deleteClick(item: any) {

  const ids = [item.id].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    contentConfig.deleteAction(ids).then(() => {
      ElMessage.success("删除成功");
      handleQueryClick();
    });

  });

}
// 新增
async function handleAddClick() {
  addSkuModalRef.value?.open()
  // myDialogRef.value?.open();
  // addModalRef.value?.setModalVisible();
  // 加载上级规格下拉数据源 
  // addModalConfig.formItems[2]!.attrs!.data = await UserAPI.getPage({ name: "" });
  // 加载角色下拉数据源
  // addModalConfig.formItems[4]!.options = await RoleAPI.getOptions();
}
// 编辑
async function handleEditClick(row: IObject) {
  addSkuModalRef.value?.open(row)
  // editModalRef.value?.handleDisabled(false);
  // // 加载部门下拉数据源
  // editModalConfig.formItems[2]!.attrs!.data = [{
  //   createTime: "",
  //   fullName: "顶级",
  //   id: "0", level: 1,
  //   name: "顶级",
  //   pid: "0",
  //   pids: "0,",
  //   shopId: "1",
  //   sort: 1,
  //   status: 1,
  //   updateTime: "",
  //   children: await UserAPI.getPage({ name: "" })
  // }]
  // 加载角色下拉数据源
  // editModalConfig.formItems[4]!.options = await RoleAPI.getOptions();
  // 根据id获取数据进行填充
  // const data = await UserAPI.getunitinfo(row.id);
  // editModalRef.value?.setFormData(data);
  // editModalRef.value?.setModalVisible();

}
// 其他工具栏
function handleToolbarClick(name: string) {
  console.log(name);
  if (name === "custom1") {
    ElMessage.success("点击了自定义1按钮");
  }
}
// 其他操作列
async function handleOperatClick(data: IOperatData) {
  console.log(data);
  // 重置密码
  if (data.name === "reset_pwd") {
    ElMessageBox.prompt("请输入用户「" + data.row.username + "」的新密码", "重置密码", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
    }).then(({ value }) => {
      if (!value || value.length < 6) {
        ElMessage.warning("密码至少需要6位字符，请重新输入");
        return false;
      }
      // UserAPI.resetPassword(data.row.id, value).then(() => {
      //   ElMessage.success("密码重置成功，新密码是：" + value);
      // });
    });
  } else if (data.name === "detail") {
    // 禁用表单编辑
    editModalRef.value?.handleDisabled(true);
    // 打开抽屉
    editModalRef.value?.setModalVisible();
    // 修改抽屉标题
    editModalConfig.drawer = { ...editModalConfig.drawer, title: "用户详情" };
    // 加载部门下拉数据源
    // editModalConfig.formItems[2]!.attrs!.data = await DeptAPI.getOptions();
    // 加载角色下拉数据源
    // editModalConfig.formItems[4]!.options = await RoleAPI.getOptions();
    // 根据id获取数据进行填充
    // const formData = await UserAPI.getFormData(data.row.id);
    // 设置表单数据
    // editModalRef.value?.setFormData(formData);
  }
}

// 切换示例
const isA = ref(true);
</script>

<style scoped lang="scss">
.tag_wrap {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.input-new-tag {
  width: 180px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
