<template>
  <div class="container" style="height: 100%">
    <el-row>
      <el-col :span="2">
        <el-scrollbar :style="{ height: innerHeight - 50 + 'px' }">
          <el-autocomplete v-model="state" :fetch-suggestions="querySearch" popper-class="my-autocomplete" placeholder="搜索下单产品" @select="handleSelect">
            <template #prefix>
              <el-icon class="el-input__icon"><search /></el-icon>
            </template>
            <template #default="{ item }">
              <div class="value">{{ item.title }}</div>
              <!-- <span class="link">{{ item.id }}</span> -->
            </template>
          </el-autocomplete>
          <el-menu ref="menuRef" :default-active="active" class="el-menu-vertical-demo" @select="handleOpen" @close="handleClose">
            <template v-for="item in menu">
              <el-menu-item :index="`${item.id}`" style="border: unset">
                <span>{{ item.title }}</span>
              </el-menu-item>
            </template>
          </el-menu>
        </el-scrollbar>
      </el-col>
      <el-col :span="22">
        <el-scrollbar style="background-color: #f8f8f8; padding: 10px" :style="{ height: innerHeight - 50 + 'px' }">
          <div style="border-left: 4px solid #ffc400; border-bottom: 2px solid #eee; background-color: #ffffff; padding: 16px">
            <span style="font-size: 20px; font-weight: bold">在线报价：{{ product.title }}</span>
          </div>
          <el-form ref="submitFormRef" :rules="rules" :model="submitFormData" style="background-color: #ffffff; padding: 16px" v-if="product.id">
            <div class="el-flex margin_bottom">
              <div class="mater_title">材料</div>
              <el-form-item prop="materialId">
                <el-radio-group class="custom-radio-group" v-model="submitFormData.materialId" @change="materialChange">
                  <el-radio class="radio_button" border v-for="item in material" :key="item.id" :label="item.id">{{ item.title }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>
            <div class="el-flex margin_bottom" style="align-items: center">
              <div class="mater_title">客户旺旺</div>
              <el-form-item prop="wangwang">
                <el-input v-model="submitFormData.wangwang" placeholder="请输入客户旺旺" style="width: 200px"></el-input>
              </el-form-item>
            </div>
            <div class="el-flex margin_bottom" style="align-items: center">
              <div class="mater_title">规格</div>
              <el-form-item prop="width">
                <el-input v-model="submitFormData.width" placeholder="请输入宽度" style="width: 120px"></el-input>
              </el-form-item>
              <el-icon style="margin: 0 15px"><Close /></el-icon>
              <el-form-item prop="height">
                <el-input v-model="submitFormData.height" placeholder="请输入高度" style="width: 120px"></el-input>
              </el-form-item>
            </div>
            <div class="el-flex margin_bottom" style="align-items: center" v-if="product.isMore">
              <div class="mater_title">规格2</div>
              <el-form-item prop="width">
                <el-input v-model="submitFormData.width2" placeholder="请输入宽度" style="width: 120px"></el-input>
              </el-form-item>
              <el-icon style="margin: 0 15px"><Close /></el-icon>
              <el-form-item prop="height">
                <el-input v-model="submitFormData.height2" placeholder="请输入高度" style="width: 120px"></el-input>
              </el-form-item>
            </div>
            <div class="el-flex margin_bottom" style="align-items: center">
              <div class="mater_title">款数</div>
              <el-form-item prop="number">
                <el-input v-model="submitFormData.number" placeholder="请输入款数" style="width: 120px"></el-input>
              </el-form-item>
            </div>
            <el-divider />
            <div class="el-flex margin_bottom" style="align-items: flex-start" v-if="product != null || material != null">
              <div class="mater_title" style="margin-top: 5px">工艺</div>
              <div>
                <el-checkbox-group v-model="craftId">
                  <template v-for="item in cates">
                    <div class="el-flex" style="padding-top: 5px; padding-bottom: 10px" v-if="item.children?.length > 0">
                      <span class="craftt_cate_name">{{ item.title }}</span>
                      <template v-for="(craft, index) in item.children" :key="index">
                        <el-checkbox :checked="craft.checked" :disabled="craft.disabled" :label="craft.id" style="margin-left: 10px" @change="checked => checkBoxChange(checked, craft, item.id)">
                          {{ craft.title }}
                        </el-checkbox>
                        <template v-if="craft.checked && craft?.params && craft?.params?.length > 0">
                          <el-select v-model="craftParamsId[craft.id]" style="width: 100px; margin-left: 10px">
                            <el-option v-for="(param, i) in craft.params" :key="i" :label="param.title" :value="param.id" />
                          </el-select>
                        </template>
                      </template>
                    </div>
                  </template>
                </el-checkbox-group>
              </div>
            </div>
            <div class="el-flex margin_bottom" style="align-items: center">
              <div class="mater_title">数量</div>
              <div class="el-flex">
                <el-form-item prop="count" style="margin-right: 16px">
                  <el-input v-model="submitFormData.count" placeholder="自定义数量" style="width: 120px"></el-input>
                </el-form-item>
                <el-button type="primary" @click="computeSubmit">计算价格</el-button>
              </div>
            </div>
            <div class="el-flex margin_bottom">
              <div class="mater_title">计算结果</div>
              <div class="el-flex">
                <el-input type="textarea" resize="none" v-model="textAreaValue" readonly input-style="width: 500px; height: 200px" />
              </div>
            </div>
          </el-form>
        </el-scrollbar>
      </el-col>
    </el-row>
  </div>
</template>
<script setup name="FrontProduct">
import { getList, getProductDetail, getProductCompute } from '@/api/front/product';
import { saveLog } from '@/api/front/quoteLog';

const { proxy } = getCurrentInstance();

const menu = ref([]);
const state = ref('');
const innerHeight = ref(0);
const active = ref('');

const product = ref({});
const material = ref([]);
const productCates = ref([]);
const materialCates = ref([]);
const cates = ref([]);
let repels = [];
const craftParamsId = ref({});
const craftId = ref([]);
const computeData = reactive({
  submitFormData: { productId: null, materialId: null, number: 1 },
  rules: {
    wangwang: [{ required: true, message: '旺旺不能为空', trigger: 'blur' }],
    width: [{ required: true, message: '宽度不能为空', trigger: 'blur' }],
    height: [{ required: true, message: '高度不能为空', trigger: 'blur' }],
    count: [{ required: true, message: '数量不能为空', trigger: 'blur' }],
  },
});
const { submitFormData, rules } = toRefs(computeData);

const textAreaValue = ref('');
function computeSubmit() {
  proxy.$refs['submitFormRef'].validate(valid => {
    if (valid) {
      let formData = { ...submitFormData.value };
      if (Object.keys(craftParamsId.value)?.length > 0) {
        formData.craftParamsId = Object.values(craftParamsId.value);
      }
      if (Object.keys(craftId.value)?.length > 0) {
        formData.craftId = Object.values(craftId.value);
      }
      console.log('🚀 ~ file: index.vue:131 ~ computeSubmit ~ formData:', formData);
      getProductCompute(formData).then(res => {
        let { code, data, msg } = res;
        if (code == 200) {
          let title = '';
          let logTitle = '';
          title = product.value.title;
          logTitle = product.value.title;
          if (formData.materialId) {
            title = title + '-' + material.value.find(item => item.id == formData.materialId).title;
            logTitle = logTitle + '-' + material.value.find(item => item.id == formData.materialId).title;
          }
          title = title + '-' + formData.width + '*' + formData.height + '厘米\n';
          logTitle = logTitle + '-' + formData.width + '*' + formData.height + '厘米';
          if (formData.craftId && formData.craftId.length > 0) {
            title = title + '工艺：';
            let crafts = [];
            for (let i = 0; i < formData.craftId.length; i++) {
              cates.value.map(item => {
                item.children.map(e => {
                  if (e.id == formData.craftId[i]) {
                    crafts.push(e.title);
                  }
                });
              });
            }
            title = title + crafts.join('、') + '\n';
            logTitle = logTitle + '-' + crafts.join('-') + '';
          }
          if (data && data.length > 0) {
            let i = 0;
            data.forEach(item => {
              title = title + formData.number + '款 各' + item.count + '个' + ',共' + item.price + '元\n';
              if (i == 0) {
                logTitle = logTitle + '-' + formData.number + '款-' + item.count;
                i++;
              }
            });
          }
          title = title + '包邮，免费设计呢~（偏远地区需补邮费）';
          console.log('🚀 ~ file: index.vue:171 ~ getProductCompute ~ title:', title);
          textAreaValue.value = title;
          logTitle = logTitle + '-' + formData.wangwang;
          saveLog({ wangwang: formData.wangwang, productId: formData.productId, content: logTitle });
        }
        console.log('🚀 ~ file: index.vue:127 ~ getProductCompute ~ res:', res);
      });
    }
  });
}

//获取商品详情
async function handleOpen(key, keyPath) {
  let { code, msg, data } = await getProductDetail(key);
  if (code == 200) {
    resetForm();
    submitFormData.value.productId = key;
    product.value = data;
    material.value = data.productMaterials;
    productCates.value = data.productCates;
    showCraft();
  }
}

function resetForm() {
  product.value = {};
  material.value = [];
  productCates.value = [];
  materialCates.value = [];
  cates.value = [];
  repels = [];
  craftParamsId.value = [];
  craftId.value = [];
  submitFormData.value = { productId: null, materialId: null, number: 1 };
}

function handleClose(key, keyPath) {
  console.log(key, keyPath);
}
async function getProductList() {
  innerHeight.value = window.innerHeight;
  let { code, msg, data } = await getList();
  if (code === 200) {
    menu.value = data;
  }
}
//材料改变
function materialChange(event) {
  material.value?.map(item => {
    if (item.id === event) {
      materialCates.value = item.productCates;
    }
  });
  showCraft();
}
//筛选显示的工艺
function showCraft() {
  craftId.value = [];
  cates.value = [...productCates.value];
  cates.value = cates.value.filter(item => {
    return !materialCates.value.some(e => item.title === e.title);
  });
  cates.value = [...cates.value, ...materialCates.value];

  cates.value?.forEach(item => {
    item.children?.forEach(e => {
      e.checked = false;
      e.disabled = false;
      if (!Array.isArray(e.repel)) {
        e.repel = e?.repel?.split('|');
      }
    });
    if (item.isReq) {
      for (let index = 0; index < item.children.length; index++) {
        if (repels.length > 0 && repels.includes(item.children[index].title)) {
          continue;
        }
        item.children[index].checked = true;
        craftId.value.push(item.children[index].id);
        setRepel();
      }
    }
  });
}

//选中选项
function checkBoxChange(value, item, id) {
  item.checked = value;
  setReq(item, id);
  setOnly(value, item, id);
  setRepel();
  setParams();
}

function setReq(item, id) {
  let cate = cates.value?.find(e => e.id === id);
  let title = [];
  if (cate.isReq) {
    let all = cate.children.every(e => {
      title.push(e.title);
      return !e.checked;
    });
    if (all) {
      proxy.$modal.msg(title.join('、') + ' 必须选择一个');
      craftId.value.push(item.id);
      item.checked = true;
    }
  }
}
function setOnly(value, item, id) {
  let cate = cates.value?.find(e => e.id === id);
  if (cate.isOnly && item.checked) {
    cate.children.forEach(e => {
      if (e.id !== item.id) {
        e.checked = false;
        craftId.value = craftId.value.filter(k => k !== e.id);
      }
    });
  }
}
//设置互斥项
function setRepel() {
  let list = [];
  cates.value?.forEach(item => {
    item.children?.forEach(e => {
      if (e.checked && e?.repel?.length > 0) {
        list = [...list, ...e.repel];
      }
    });
  });

  repels = [...new Set(list)]; // 去重

  cates.value?.forEach(item => {
    item.children?.forEach(e => {
      e.disabled = false;
      if (repels.length > 0 && repels.includes(e.title)) {
        e.disabled = true;
      }
    });
  });
}

function setParams() {
  cates.value?.forEach(item => {
    item.children?.forEach(e => {
      if (!e.checked && e.params?.length > 0) {
        e.params.forEach(p => {
          console.log('🚀 ~ file: index.vue:329 ~ craftParamsId.value.map ~ craftParamsId.value:', craftParamsId.value);
          let list = {};
          Object.keys(craftParamsId?.value).map(k => {
            console.log('🚀 ~ file: index.vue:326 ~ Object.values ~ k:', k);
            console.log('🚀 ~ file: index.vue:328 ~ Object.values ~ e:', e);
            if (p.id !== craftParamsId?.value[k]) {
              list[k] = craftParamsId?.value[k];
            }
          });
          console.log('🚀 ~ file: index.vue:327 ~ craftParamsId.value.map ~ list:', list);
          craftParamsId.value = list;
        });
      }
    });
  });
}

function handleSelect(item) {
  active.value = `${item.id}`;
  state.value = item.title;
}

function querySearch(queryString, callback) {
  let result = menu.value?.map(item => {
    return { title: item.title, id: item.id };
  });
  queryString ? callback(result.filter(item => item.title.indexOf(queryString) === 0)) : callback(result);
}
getProductList();
</script>
<style lang="scss" scoped>
.container {
  font-size: 14px;
  .mater_title {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-shrink: 0;
    width: 105px;
    color: #333;
    text-align: center;
    height: 36px;
    border-radius: 3px;
    background: #fdf4d7;
    margin-right: 16px;
  }
  .radio_button {
    margin-left: 0;
    margin-bottom: 10px;
    padding: 2px;
    display: flex;
    align-items: center;
    justify-content: center;
    float: left;
    white-space: normal;
    height: 40px;
    width: 210px;
  }
}
.margin_bottom {
  margin-bottom: 16px;
}
.craftt_cate_name {
  display: inline-block;
  height: 36px;
  width: 84px;
  line-height: 36px;
  background: #f8f8f8;
  text-align: center;
  margin-right: 10px;
  font-size: 10px;
  color: #999;
}
/**修改el样式 */
:deep(.custom-radio-group .el-radio__input) {
  display: none;
}
:deep(.el-radio.is-bordered.is-checked) {
  border-color: #ffc400;
}
:deep(.el-radio__input.is-checked + .el-radio__label) {
  color: #ffc400;
}
:deep(.custom-radio-group .el-radio.is-bordered.is-checked::after) {
  content: '';
  position: absolute;
  bottom: 0;
  right: 0;
  display: block;
  width: 0;
  height: 0;
  border: 10px solid;
  border-color: transparent #ffc400 #ffc400 transparent;
  z-index: 9;
}
:deep(.custom-radio-group .el-radio.is-bordered.is-checked::before) {
  content: '';
  position: absolute;
  bottom: 4px;
  right: 1px;
  display: block;
  width: 10px;
  height: 6px;
  border: 2px solid;
  border-color: transparent transparent #fff #fff;
  z-index: 10;
  transform: rotate(-45deg);
}
:deep(.el-button--primary) {
  color: #333;
  background-color: #ffc400;
  border-color: #ffc400;
}
:deep(.el-button--primary:focus, .el-button--primary:hover) {
  background: #ffd033;
  border-color: #ffd033;
  color: #333;
}
:deep(.el-button--primary:active) {
  background: #e6b000;
  border-color: #e6b000;
  color: #333;
  outline: 0;
}
:deep(.el-button--primary, .el-radio-button__orig-radio:checked + .el-radio-button__inner, .el-button--primary:focus, .el-button--primary:hover) {
  color: #101010;
}
:deep(.el-form-item) {
  margin-bottom: 0;
}
:deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
  color: #ffc400;
}
:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #ffc400;
  border-color: #ffc400;
}
</style>
