<template>
  <div class="tenant">
    <div class="content">
      <byTable :source="sourceList.data" :pagination="sourceList.pagination" :config="config" :loading="loading" highlight-current-row @get-list="getList">
      </byTable>
    </div>

    <el-dialog title="修改编码规则" v-if="dialogVisible" v-model="dialogVisible" width="600" v-loading="loadingDialog">
      <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="submit">
        <template #ruleVoList>
          <div style="width: 100%">
            <div v-if="formData.data.ruleVoList && formData.data.ruleVoList.length > 0" id="sort">
              <div style="display: flex; margin-bottom: 20px" v-for="(row, index) in formData.data.ruleVoList" :key="row.timeKey" ref="sort">
                <el-form-item :prop="'ruleVoList.' + index + '.ruleType'" :rules="rules.ruleType" label="字符类型" prop="ruleType">
                  <el-select v-model="row.ruleType" placeholder="请选择字符类型" @change="changeType(row)">
                    <el-option v-for="item in ruleType" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
                <el-form-item
                  :prop="'ruleVoList.' + index + '.value'"
                  :rules="rules.value1"
                  label="  "
                  prop="value"
                  style="margin-left: 8px"
                  v-if="row.ruleType == 1">
                  <el-input v-model="row.value" placeholder="请输入自定义字符" />
                </el-form-item>
                <el-form-item
                  :prop="'ruleVoList.' + index + '.value'"
                  :rules="rules.value5"
                  label="  "
                  prop="value"
                  style="margin-left: 8px"
                  v-if="row.ruleType == 5">
                  <el-input-number v-model="row.value" placeholder="请输入自增编号位数" :precision="0" :controls="false" :min="3" />
                </el-form-item>
                <el-form-item
                  :prop="'ruleVoList.' + index + '.value'"
                  :rules="rules.value6"
                  label="  "
                  prop="value"
                  style="margin-left: 8px"
                  v-if="row.ruleType == 6">
                  <el-select v-model="row.value" placeholder="请选择日期格式">
                    <el-option v-for="item in dateList" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
                <el-icon style="margin-left: 8px; color: red; cursor: pointer; transform: translateY(37px)" @click="clickDelete(index)"><Delete /></el-icon>
              </div>
            </div>
            <div>
              <el-button type="primary" @click="clickAddRule()">添加</el-button>
            </div>
          </div>
        </template>
        <template #codingKey>
          <div style="width: 100%; text-align: center">
            <span style="font-size: 21px; font-weight: 700">{{ getCodingKey() }}</span>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="dialogVisible = false" size="large">取 消</el-button>
        <el-button type="primary" @click="submitForm()" size="large">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, ref } from "vue";
import byTable from "@/components/byTable/index";
import byForm from "@/components/byForm/index";
import { ElMessage } from "element-plus";
import Sortable from 'sortablejs';
const { proxy } = getCurrentInstance();
const ruleType = ref([
  {
    label: "自定义字符",
    value: 1,
  },
  {
    label: "客户国家代码",
    value: 2,
  },
  {
    label: "业务员代码",
    value: 3,
  },
  {
    label: "客户编码",
    value: 4,
  },
  {
    label: "自增编号",
    value: 5,
  },
  {
    label: "日期",
    value: 6,
  },
]);
const dateList = ref([
  {
    label: "YY",
    value: "yy",
  },
  {
    label: "YYYY",
    value: "yyyy",
  },
  {
    label: "YYYYMM",
    value: "yyyyMM",
  },
  {
    label: "YYYYMMDD",
    value: "yyyyMMdd",
  },
]);
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    keyword: "",
  },
});
const loading = ref(false);
const config = computed(() => {
  return [
    {
      attrs: {
        label: "功能名称",
        prop: "codingName",
        width: 260,
      },
    },
    {
      attrs: {
        label: "编号生成规则",
        prop: "codingKey",
      },
    },
    {
      attrs: {
        label: "最近操作人",
        prop: "updateUserName",
        width: 200,
      },
    },
    {
      attrs: {
        label: "操作时间",
        prop: "updateTime",
        width: 160,
      },
    },
    {
      attrs: {
        label: "操作",
        width: "120",
        align: "center",
      },
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "编辑",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              update(row);
              
            },
          },
        ];
      },
    },
  ];
});

const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy.post("/codingRule/page", sourceList.value.pagination).then((res) => {
    sourceList.value.data = res.rows;
    sourceList.value.pagination.total = res.total;
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};
getList();
const dialogVisible = ref(false);
const loadingDialog = ref(false);
const submit = ref(null);
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const formConfig = computed(() => {
  return [
    {
      type: "input",
      prop: "codingName",
      label: "功能名称",
      itemType: "text",
      disabled: true,
    },
    {
      type: "slot",
      prop: "ruleVoList",
      slotName: "ruleVoList",
      label: "编码规则",
    },
    {
      type: "slot",
      prop: "codingKey",
      slotName: "codingKey",
      label: "编码预览",
    },
  ];
});
const rules = ref({
  ruleType: [{ required: true, message: "请选择字符类型", trigger: "change" }],
  value1: [{ required: true, message: "请输入自定义字符", trigger: "blur" }],
  value5: [{ required: true, message: "请输入自增编号位数", trigger: "blur" }],
  value6: [{ required: true, message: "请选择日期格式", trigger: "change" }],
});
const formData = reactive({
  data: {
    ruleVoList: [],
  },
});
const submitForm = () => {
  submit.value.handleSubmit(() => {
    if (!(formData.data.ruleVoList && formData.data.ruleVoList.length > 0)) {
      return ElMessage("请添加编码规则");
    }
    let data = formData.data.ruleVoList.filter((item) => item.ruleType === 5);
    if (data && data.length > 0) {
      if (data.length > 1) {
        return ElMessage("自增编号只能添加一次");
      }
    } else {
      return ElMessage("编码规则中必须存在一个'自增编号''");
    }
    loadingDialog.value = true;
    proxy.post("/codingRule/edit", formData.data).then(
      () => {
        ElMessage({
          message: "编辑成功",
          type: "success",
        });
        dialogVisible.value = false;
        getList();
      },
      (err) => {
        console.log(err);
        loadingDialog.value = false;
      }
    );
  });
};
const update = (row) => {
  formData.data = proxy.deepClone(row);
  formData.data.ruleVoList = formData.data.ruleVoList.map(item => {
    //timeKey
    return {
      ...item,
      timeKey: new Date().getTime() + item.value + Math.random()
    }
  })
  console.log(formData.data.ruleVoList)
  loadingDialog.value = false;
  dialogVisible.value = true;
  setTimeout(() => {
    sortableInit()
  }, 500);
};
const sort = ref()
const sortableInit = () => {
  console.log(document.getElementById('sort'))
  const el = document.getElementById('sort');
  Sortable.create(el, {
    ghostClass: "sortableActive",
    onEnd(evt) {
      const { newIndex, oldIndex } = evt
      console.log(newIndex, oldIndex)
      formData.data.ruleVoList.splice(newIndex, 0, formData.data.ruleVoList.splice(oldIndex, 1)[0])
    }
  })
}
const clickAddRule = () => {
  if (formData.data.ruleVoList && formData.data.ruleVoList.length > 0) {
    formData.data.ruleVoList.push({
      ruleType: "",
      value: "",
      timeKey:new Date().getTime(),
    });
  } else {
    formData.data.ruleVoList = [
      {
        ruleType: "",
        value: "",
        timeKey:new Date().getTime(),
      },
    ];
  }
};
const changeType = (item) => {
  if (item.ruleType === 5) {
    item.value = undefined;
  } else if ([1, 6].includes(item.ruleType)) {
    item.value = "";
  } else if (item.ruleType === 2) {
    item.value = "CHN";
  } else if (item.ruleType === 3) {
    item.value = "YWY";
  } else if (item.ruleType === 4) {
    item.value = "KH";
  }
};
const clickDelete = (index) => {
  formData.data.ruleVoList.splice(index, 1);
};
const getCodingKey = () => {
  let text = "";
  if (formData.data.ruleVoList && formData.data.ruleVoList.length > 0) {
    for (let i = 0; i < formData.data.ruleVoList.length; i++) {
      if (formData.data.ruleVoList[i].ruleType === 5) {
        for (let x = 0; x < formData.data.ruleVoList[i].value; x++) {
          if (x === formData.data.ruleVoList[i].value - 1) {
            text = text + "1";
          } else {
            text = text + "0";
          }
        }
      } else {
        text = text + formData.data.ruleVoList[i].value;
      }
    }
  }
  return text;
};

</script>
<style>
  .sortableActive{
    background: #e0dfdf;
  }
</style>
<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
::v-deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style>
