<template>
  <div>
    <Toptitle :title="setTip">
      <Button @click="back" type="primary" ghost style="margin-right:10px;"
        >返回</Button
      >
      <Button v-if="type != 3" type="primary" @click="handleSubmit('Info')"
        >保存</Button
      >
    </Toptitle>

    <div class="page-edit">
      <Form inline ref="Info" :model="info" :rules="rules" :label-width="120">
        <FormItem label="产品分类" prop="bp_id">
          <Select
            v-if="type != 3"
            style="width:300px"
            v-model="info.bp_id"
            @on-change="changeProduct"
          >
            <Option
              v-for="item of productFiled"
              :key="item.id"
              :value="item.id"
              :label="item.title"
            ></Option>
          </Select>
          <span v-else>{{
            productFiled.length > 0 && info.bp_id
              ? productFiled.filter((item) => item.id == info.bp_id)[0].title
              : ""
          }}</span>
        </FormItem>
        <FormItem label="产品名称" prop="title">
          <Input
            v-if="type != 3"
            v-model="info.title"
            style="width:300px"
            placeholder="请输入产品名称"
          />
          <span v-else>{{ info.title }}</span>
        </FormItem>
        <FormItem label="计量单位" prop="unit">
          <Input
            v-if="type != 3"
            v-model="info.unit"
            style="width:300px"
            placeholder="请输入计量单位"
          />
          <span v-else>{{ info.unit }}</span>
        </FormItem>
        <FormItem label="型号" prop="model">
          <Input
            v-if="type != 3"
            v-model="info.model"
            style="width:300px"
            placeholder="请输入产品型号"
          />
          <span v-else>{{ info.model }}</span>
        </FormItem>
        <FormItem label="图号" prop="title">
          <Input
            v-if="type != 3"
            v-model="info.url_number"
            style="width:300px"
            placeholder="请输入图号"
          />
          <span v-else>{{ info.url_number }}</span>
        </FormItem>
        <!-- <FormItem label="安全预警" prop='title'>
                    <Input :disabled='type == 3' v-model="info.min_stock" style="width:300px" placeholder="请输入安全预警"></Input>
                </FormItem>
                <FormItem label="最高预警" prop='title'>
                    <Input :disabled='type == 3' v-model="info.max_stock" style="width:300px" placeholder="请输入最高预警"></Input>
                </FormItem> -->
        <!-- <FormItem label="是否加锁">
          <div style="display:flex;min-width:300px;">
            <RadioGroup v-model="info.lucy_type">
              <Radio :disabled='type == 3'
                     :label="1">是</Radio>
              <Radio :disabled='type == 3'
                     :label="0">否</Radio>
            </RadioGroup>
            <Select :disabled='type == 3'
                    v-model="info.luck"
                    v-if="info.lucy_type == 1"
                    style="width:150px;">
              <Option v-for="item of lucks"
                      :key="item.id"
                      :value='item.id'>{{item.title }}</Option>
            </Select>
          </div>
        </FormItem> -->
      </Form>
      <div class="view-filed">
        <span>基础测量字段</span>
        <div class="filed-item">
          <div v-for="item of measureList" :key="item.id">
            {{ item.title }}({{ item.e_title }})
          </div>
        </div>
      </div>
      <div class="table-log">
        <div>
          <span>部件添加：</span>
          <Button
            :disabled="type == 3"
            type="primary"
            size="small"
            ghost
            @click="addPart"
            >新增部件</Button
          >
        </div>
        <span>计算公式请使用英文字母参与公式运算，详细请参考例)</span>
      </div>
      <vxe-table
        resizable
        border
        ref="xTree"
        :tree-config="treeConfig"
        :data="info.part"
        @toggle-tree-expand="toggleExpandChangeEvent"
      >
        <vxe-table-column field="title" title="部件名称" tree-node>
          <template #default="{ row }">
            <Select
              filterable
              v-if="type != 3"
              clearable
              transfer
              v-model="row.part_id"
            >
              <Option
                v-for="(item, key) of parts"
                :key="key"
                :value="item.id"
                :label="item.title"
              ></Option>
            </Select>
            <span v-else>{{
              parts.length > 0 && row.part_id
                ? parts.filter((item) => item.id == row.part_id)[0].title
                : ""
            }}</span>
          </template>
        </vxe-table-column>
        <vxe-table-column field="formula_l" title="高(H)">
          <template #default="{ row,rowIndex }">
            <Input
              v-if="type != 3"
              @on-focus="openKey(rowIndex, 'formula_l', row)"
              clearable
              placeholder="请输入公式"
              v-model="row.formula_l"
            />
            <span v-else>{{ row.formula_l }}</span>
          </template>
        </vxe-table-column>
        <vxe-table-column field="formula_w" title="宽(W)">
          <template #default="{ row,rowIndex }">
            <Input
              v-if="type != 3"
              @on-focus="openKey(rowIndex, 'formula_w', row)"
              clearable
              placeholder="请输入公式"
              v-model="row.formula_w"
            />
            <span v-else>{{ row.formula_w }}</span>
          </template>
        </vxe-table-column>
        <vxe-table-column field="formula_h" title="厚(T)">
          <template #default="{ row,rowIndex }">
            <Input
              v-if="type != 3"
              @on-focus="openKey(rowIndex, 'formula_h', row)"
              clearable
              placeholder="请输入公式"
              v-model="row.formula_h"
            />
            <span v-else>{{ row.formula_h }}</span>
          </template>
        </vxe-table-column>
        <vxe-table-column field="ratio" title="产值比例(%)">
          <template #default="{ row }">
            <Input
              v-if="type != 3"
              clearable
              placeholder="请输入产值比例"
              v-model="row.ratio"
            />
            <span v-else>{{ row.ratio }}</span>
          </template>
        </vxe-table-column>
        <vxe-table-column field="is_null" title="默认为空">
          <template #default="{ row }">
            <Select
              filterable
              v-if="type != 3"
              clearable
              transfer
              v-model="row.is_null"
            >
              <Option :value="1" label="是"></Option>
              <Option :value="0" label="否"></Option>
            </Select>
            <span v-else>{{ row.is_null==1?'是':'否' }}</span>
          </template>
        </vxe-table-column>
        <vxe-table-column field="set" width="180" title="操作">
          <template #default="{ row,rowIndex }">
            <Button
              v-if="type != 3"
              size="small"
              type="error"
              style="margin-right:10px"
              @click="delPart(row, rowIndex)"
              >删除</Button
            >
            <Button
              size="small"
              type="primary"
              v-if="row.detail && type != 3"
              @click="addReplacePart(info.part, rowIndex)"
              >增加替换项</Button
            >
          </template>
        </vxe-table-column>
      </vxe-table>
      <!-- <Table class="overflow-table"
             style="margin-bottom:40px;"
             stripe
             border
             row-key="index"
             :columns="tableColums"
             :data="info.part">
        <template slot='title'
                  slot-scope='{row,index}'>
          <div>
            <Select filterable
                    :disabled='type == 3'
                    clearable
                    v-model="row.part_id">
              <Option v-for="(item,key) of parts"
                      :key="key"
                      :value='item.id'
                      :label="item.title"></Option>
            </Select>
          </div>
        </template>
        <template slot='formula_l'
                  slot-scope='{row,index}'>
          <div>
            <Input :disabled='type == 3'
                   @on-focus="openKey(index,'formula_l',row)"
                   clearable
                   placeholder="请输入公式"
                   v-model="row.formula_l"></Input>
          </div>
        </template>
        <template slot='formula_w'
                  slot-scope='{row,index}'>
          <div>
            <Input :disabled='type == 3'
                   @on-focus="openKey(index,'formula_w',row)"
                   clearable
                   placeholder="请输入公式"
                   v-model="row.formula_w"></Input>
          </div>
        </template>
        <template slot='formula_h'
                  slot-scope='{row,index}'>
          <div>
            <Input :disabled='type == 3'
                   @on-focus="openKey(index,'formula_h',row)"
                   clearable
                   placeholder="请输入公式"
                   v-model="row.formula_h"></Input>
          </div>
        </template>
        <template slot='ratio'
                  slot-scope='{row,index}'>
          <div>
            <Input :disabled='type == 3'
                   clearable
                   placeholder="请输入产值比例"
                   v-model="row.ratio"></Input>
          </div>
        </template>
        <template slot='del'
                  slot-scope='{row,index}'>
          <div>
            <Button :disabled='type == 3'
                    size='small'
                    type="error"
                    style="margin-right:10px"
                    @click="delPart(info.part,index)">删除</Button>
            <Button :disabled='type == 3'
                    size='small'
                    type="primary"
                    v-show="row.children"
                    @click="addReplacePart(info.part,index)">增加替换项</Button>
          </div>
        </template>
      </Table> -->

      <div class="custom">
        <span class="custom-title"
          >产品自定义属性
          <Button
            :disabled="type == 3"
            style="margin:10px;margin-left:20px;"
            size="small"
            type="primary"
            @click="addCustom"
            ghost
          >
            新增自定义属性
          </Button>
        </span>
        <div class="modal-custom">
          <div
            class="modal-custom-item"
            v-for="(item, index) of info.remark"
            :key="index"
          >
            <div class="left">
              {{ "自定义属性:" + (index + 1) }}
            </div>
            <div class="right">
              <div class="radio">
                <RadioGroup
                  @on-change="(e) => handleContentTypeChange(e, item)"
                  v-model="item.type"
                >
                  <Radio :disabled="type == 3" :label="1">输入框</Radio>
                  <Radio :disabled="type == 3" :label="2">单选框</Radio>
                </RadioGroup>
              </div>

              <div
                class="attr"
                style="display:flex;flex-wrap:wrap;justify-content: flex-start;"
              >
                <Input
                  :disabled="type == 3"
                  v-model="item.title"
                  style="width:180px;margin-right: 30px;"
                  placeholder="请输入属性名称"
                ></Input>
                <Input
                  :disabled="type == 3"
                  v-if="item.type == 1"
                  v-model="item.content"
                  style="width:360px;"
                  placeholder="请输入属性内容"
                ></Input>
                <div v-else>
                  <div
                    v-for="(_item, _index) in item.content"
                    style="width:300px;display:flex;align-content: flex-end;align-items: center;flex-wrap:wrap;padding-bottom:10px"
                    :key="_item + '' + _index"
                  >
                    <Input
                      :disabled="type == 3"
                      v-model="_item.value"
                      style="width:240px;"
                      placeholder="请输入属性内容"
                    ></Input>
                    <Icon
                      type="ios-add"
                      @click="handleContentAdd(item.content)"
                      size="24"
                    />
                    <Icon
                      type="ios-remove"
                      v-show="item.content.length != 1"
                      @click="handleContentRemove(item.content, _index)"
                      size="24"
                    />
                  </div>
                </div>
              </div>
            </div>
            <Icon
              v-if="type != 3"
              @click="delItems(index, info.remark)"
              size="20"
              class="delete-img"
              type="ios-close-circle"
            />
          </div>
        </div>
      </div>
      <div class="product-img">
        <span>产品图片</span>
        <div class="product-add">
          <div class="items" v-for="(item, index) of info.img" :key="index">
            <img @click="looks(item)" :src="$store.state.ip + item" alt="" />
            <Icon
              v-if="type != 3"
              size="20"
              @click="delItems(index, info.img)"
              class="delete-img"
              type="ios-close-circle"
            />
          </div>

          <div class="add-items" v-if="type != 3">
            <div class="item">
              <Icon size="50" type="ios-add" />
            </div>

            <span>支持jpg/png格式</span>
            <input
              @change="changeIpt($event, info.img)"
              type="file"
              class="ipt"
            />
          </div>
        </div>
      </div>
      <div class="product-img">
        <span>图纸</span>
        <div class="product-add">
          <div class="items" v-for="(item, index) of info.url" :key="index">
            <img @click="looks(item)" :src="$store.state.ip + item" alt="" />
            <Icon
              v-if="type != 3"
              size="20"
              @click="delItems(index, info.url)"
              class="delete-img"
              type="ios-close-circle"
            />
          </div>

          <div class="add-items" v-if="type != 3">
            <div class="item">
              <Icon size="50" type="ios-add" />
            </div>

            <span>支持jpg/png格式</span>
            <input
              @change="changeIpt($event, info.url)"
              type="file"
              class="ipt"
            />
          </div>
        </div>
      </div>

      <Modal
        v-model="showKey"
        :width="1250"
        :mask-closable="false"
        :closable="false"
      >
        <div>
          <KeyBoard
            :rightData="measureList"
            @cancel="cancelKey"
            @success="successKey"
            class="key-co"
          />
        </div>
        <div slot="footer"></div>
      </Modal>
    </div>
  </div>
</template>

<script>
import KeyBoard from "../../components/keyboard/index";
import XEUtils from "xe-utils";

export default {
  data() {
    return {
      type: 1,
      id: null,
      addImgList: [], //上传图片列表
      customList: [], //自定义属性列表
      customInfo: {}, //自定义属性对象
      productFiled: [],
      measureList: [], //基础测量展示字段(仅展示)
      lucks: [],
      tableColums: [
        {
          title: "部件名称",
          align: "center",
          key: "title",
          slot: "title",
          tree: true,
        },
        {
          title: "高(H)",
          align: "center",
          key: "formula_l",
          slot: "formula_l",
        },
        {
          title: "宽(W)",
          align: "center",
          key: "formula_w",
          slot: "formula_w",
        },
        {
          title: "厚(T)",
          align: "center",
          key: "formula_h",
          slot: "formula_h",
        },
        { title: "产值比例(%)", align: "center", key: "ratio", slot: "ratio" },
        { title: "操作", align: "center", slot: "del", minWidth: 100 },
      ],
      showCustom: false, //
      info: {
        model: "", //类型
        bp_id: "", //产品类型
        title: "", //名称
        unit: "", //单位
        img: [], //图片列表
        part: [], //部件,
        remark: [], //自定义属性列表
        lock: 0,
        lucy_type: 0,
        id: "",
        url: [],
        url_number: "",
      },
      rules: {
        bp_id: [{ required: true, message: " " }],
        model: [{ required: true, message: " ", trigger: "blur" }],
        title: [{ required: true, message: " ", trigger: "blur" }],
        unit: [{ required: true, message: " ", trigger: "blur" }],
      },
      addObj: {
        title: "",
        formula_l: "",
        formula_w: "",
        formula_h: "",
        ratio: "",
        url: "",
        url_number: "",
      },
      parts: [],
      showKey: false,
      attrindex: null,
      attrName: "",
      headers: { Authorization: localStorage.getItem("token") },
      currencyChoose: {},
      treeConfig: { children: "detail" },
    };
  },
  created() {
    this.changeProduct(this.$route.query.back_id);
  },
  mounted() {
    this.getPartsData(this.$route.query.back_id);
    this.type = this.$route.query.type || 1;
    this.id = this.$route.query.id || null;
    this.info.bp_id =
      this.type == 1 ? this.$route.query.back_id * 1 : this.info.bp_id;
    if (this.id) {
      this.getData(this.id);
    }
    this.getLocks();
  },
  components: {
    KeyBoard,
  },
  computed: {
    setTip() {
      const { type } = this.$route.query;
      const inner =
        type == 1
          ? "新增产品"
          : type == 2
          ? "编辑产品"
          : type == 3
          ? "查看产品"
          : "拷贝产品";
      return inner;
    },
  },
  methods: {
    postData() {
      if (this.info.part.length < 1) {
        return this.$Message.warning("请新增部件");
      }
      const val = this.info.part.reduce(
        (pre, cur) => (pre += cur.ratio * 1),
        0
      );
      console.log(val);
      if (val != 100) {
        return this.$Message.error("产值比列不匹配");
      }
      const { type } = this.$route.query;
      if (type == 1 || type == 4) {
        if (type == 4) {
          this.info.id = "";
        }
        this.info.op = "add";
      } else {
        this.info.op = "edit";
      }
      let data = JSON.parse(JSON.stringify(this.info));
      data.img = JSON.stringify(data.img);
      data.url = JSON.stringify(data.url);
      data.part = JSON.stringify(data.part);
      data.remark = JSON.stringify(data.remark);
      this.axios.post("/api/product_edit", data).then((res) => {
        if (res.code == 200) {
          this.$Message.success(res.msg);
          setTimeout(() => {
            this.$router.push({
              path: "/cms/product/index",
              query: {
                title: this.$route.query.title || this.$route.params.title,
                id: this.$route.query.back_id || this.$route.params.back_id,
              },
            });
          }, 500);
        }
      });
    },
    back() {
      this.$router.push({
        path: "/cms/product/index",
        query: {
          id: this.$route.query.back_id ? this.$route.query.back_id : "",
          title: this.$route.query.title || this.$route.query.title || "",
        },
      });
    },
    goPage(n, row) {
      this.$router.push({
        name: "PageEdit",
        params: {
          title: this.info.part.length >= 1 ? "编辑部件" : "新增部件",
          list: this.list,
          type: "部件",
        },
      });
    },
    handleContentTypeChange(val, item) {
      val == 1 ? (item.content = "") : (item.content = [{ value: "" }]);
      this.$forceUpdate();
    },
    openCustom() {
      this.showCustom = true;
    },
    delItems(n, arr) {
      arr.splice(n, 1);
    },
    addCustom() {
      //添加自定义属性
      if (this.info.remark.length == 0) {
        this.info.remark = [{title:'',content:'',type:1}];
      }else{
        this.info.remark.push({ title: "", content: "", type: 1 });
      }
      
    },
    postImg(file, row) {
      let formData = new FormData();
      formData.append("file", file);
      this.axios.post("/api/upload_pic", formData).then((res) => {
        row.push(res.data.url);
      });
    },
    changeIpt(e, row) {
      if (this.info.img.length >= 3) {
        return this.$Message.warning("图片最多上传3张");
      }
      let file = e.target.files[0];
      this.postImg(file, row);
      e.target.value = null;
    },
    getProductFiledData(id) {
      this.axios("/api/basics_product_index").then((res) => {
        this.productFiled = res.data.data;
      });
    },
    getData(row) {
      this.axios("/api/product", { params: { id: row } }).then((res) => {
        this.info = res.data;
        if (!this.info.url) {
          this.info.url = [];
        }
        this.info.part.forEach((element, index) => {
          element.detail.forEach((elem, idx) => {
            elem.index = index + "," + idx;
          });
        });
      });
    },
    getPartsData(id) {
      this.axios("/api/parts_index").then((res) => {
        this.parts = res.data.data;
      });
    },
    addPart() {
      let add = JSON.parse(JSON.stringify(this.addObj));
      add.index = this.info.part.length;
      add.detail = [];
      this.info.part.push(add);
    },
    addReplacePart(row, n) {
      let add = JSON.parse(JSON.stringify(this.addObj));
      add.index = n + "," + row[n].detail.length;
      add.formula_h = row[n].formula_h;
      add.formula_l = row[n].formula_l;
      add.formula_w = row[n].formula_w;
      row[n].detail.push(add);
    },
    toggleExpandChangeEvent() {},
    delPart(row, n) {
      // row.splice(n, 1)
      if (row.detail) {
        this.info.part.splice(n, 1);
      } else {
        console.log("row :>> ", row);
        // let idx = row.index.split(",");
        // this.info.part[idx[0]].detail.splice(idx[1], 1);
        console.log("this.treeConfig :>> ", this.treeConfig);
        const matchObj = XEUtils.findTree(
          this.info.part,
          (item) => item === row,
          this.treeConfig
        );
        if (matchObj) {
          // 从树节点中移除
          matchObj.items.splice(matchObj.index, 1);
        }
      }
    },
    openKey(row, attr, cur) {
      this.showKey = true;
      this.attrindex = row;
      this.attrName = attr;
      this.currencyChoose = cur;
    },
    successKey(str) {
      // this.info.part[this.attrindex][this.attrName] = str;
      this.currencyChoose[this.attrName] = str;
      this.showKey = false;
    },
    cancelKey() {
      this.showKey = false;
    },
    handleSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.postData();
        }
      });
    },
    changeProduct(e) {
      this.axios("/api/basics_product_list", { params: { id: e } }).then(
        (res) => {
          if (res.code == 200) {
            const { data } = res;
            const result = data.filter((rows) => rows.id == e);
            this.productFiled = data;
            this.measureList = result[0].measure;
          }
        }
      );
      this.getPartsData(e);
    },
    uploadSuccess(e) {
      this.info.url = e.data.url;
    },
    getLocks() {
      this.axios("/api/lock_list").then((res) => {
        if (res.code == 200) {
          this.lucks = res.data;
        }
      });
    },
    looks(img) {
      const array = [{ img_url: img }];
      this.$previewImg({
        list: array,
        baseUrl: this.$store.state.ip,
        baseImgField: "img_url",
        baseTitleField: "",
      });
    },
    handleContentAdd(list) {
      list.push({});
    },
    handleContentRemove(list, index) {
      list.splice(index, 1);
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/.ivu-table-cell {
  display: flex;
  align-items: center;
}
.page-edit {
  overflow: hidden;
  overflow-y: auto;
  position: relative;
  top: 20px;
  height: 85%;
}
.product-img {
  padding-top: 10px;
}
.product-add {
  padding: 10px 0;
  display: flex;
  flex-wrap: wrap;
  .ipt {
    position: absolute;
    width: 100%;
    height: 100%;
    opacity: 0;
    cursor: pointer;
    outline: none;
    top: 0;
    left: 0;
  }
  .add-items {
    width: 120px;
    height: 120px;
    border: 1px dotted #e7e7e7;
    border-radius: 5px;
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden;
    position: relative;
    flex-direction: column;
    background: #f4f5f7;
    .item {
      width: 46px;
      height: 46px;
      background: #3764ff;
      opacity: 0.6;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 50%;
      color: #fff;
    }
  }
  .items {
    width: 120px;
    height: 120px;
    margin-bottom: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
    background: #e7e7e7;
    margin-right: 10px;
    border-radius: 5px;
    position: relative;
    img {
      max-width: 108px;
      max-height: 108px;
    }
  }
}
.delete-img {
  position: absolute;
  right: 10px;
  top: 10px;
  color: red;
}
.custom {
  display: flex;
  flex-direction: column;
  .custom-item {
    display: flex;
    align-items: center;
    padding: 10px 0;
  }
}
.table-log {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}
.modal-custom {
  width: 100%;
  padding: 10px 0;
  display: flex;
  flex-wrap: wrap;
  .modal-custom-item {
    width: 600px;
    align-items: center;
    position: relative;
    border-radius: 5px;
    margin-right: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 7px rgba(0, 0, 0, 0.15);
    border-color: transparent;
    position: relative;
    .left {
      width: 100%;
      padding: 10px;
      background: #f4f8ff;
    }
    .right {
      width: 100%;
      border-radius: 5px;
      padding: 10px;
      .attr {
        display: flex;
        justify-content: space-between;
        margin: 5px;
      }
    }
  }
  .modal-custom-add {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    height: 109px;
    border: 1px dotted #e7e7e7;
    margin-top: 10px;
  }
}
.view-filed {
  padding: 10px 0;
  .filed-item {
    padding: 10px 0;
    display: flex;
    div {
      padding: 10px 10px;
      &:after {
        content: "|";
        margin-left: 20px;
        color: #dedede;
      }
      &:last-child {
        &:after {
          content: "";
        }
      }
    }
  }
}
/deep/ .ivu-table-wrapper {
  overflow: visible;
  color: red;
} //穿透iview
// .key-co{transform: scale(.9);}
/deep/.ivu-form-item-content {
  span {
    vertical-align: middle;
  }
}
</style>
