<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', 'item_detail')"
        >保存</Button
      >
    </Toptitle>
    <Form ref="Info" inline :model="info" :rules="rules">
      <FormItem label="ID">
        <Input
          v-model="info.id"
          disabled
          :placeholder="type == 1 || type == 2 ? '自动生成' : '12'"
        />
      </FormItem>
      <FormItem label="物料名称" prop="title">
        <Input
          :disabled="type == 3 ? true : false"
          v-model="info.title"
          placeholder="请输入物料名称"
        />
      </FormItem>
      <FormItem label="物料简称" prop="title">
        <Input
          :disabled="type == 3 ? true : false"
          v-model="info.abbreviation_title"
          placeholder="请输入物料简称"
        />
      </FormItem>
      <FormItem label="物料分类" prop="m_id">
        <Select
          filterable
          clearable
          style="width:186px;"
          v-model="info.m_id"
          :disabled="type == 3"
          placeholder="请选择材质"
        >
          <Option
            v-for="item of materialList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          ></Option>
        </Select>
      </FormItem>
      <FormItem label="厚" v-show="isShowInfoHigh" prop="high">
        <Input
          :disabled="type == 3 ? true : false"
          v-model="info.high"
          placeholder="请输入厚度"
        />
      </FormItem>
      <FormItem label="单位" prop="unit">
        <Input
          :disabled="type == 3 ? true : false"
          v-model="info.unit"
          placeholder="请输入单位"
        />
      </FormItem> 
     
      <FormItem label="损耗(%)" v-show="info.detail.length == 0" prop="scale">
        <Input
          type="number"
          :disabled="type == 3 ? true : false"
          v-model="info.scale"
          placeholder="请输入百分比"
        />
      </FormItem>
      <FormItem label="描述">
        <Input
          :disabled="type == 3 ? true : false"
          v-model="info.remark"
          placeholder="请输入描述"
        />
      </FormItem> 
      <FormItem label="上传附件:">
          <div class="product-img">
            <div class="product-add">
              <div class="img_items" v-if="this.info.img_url !== ''">
                <img
                  @click="looks(info.img_url)"
                  :src="$store.state.ip + this.info.img_url"
                  alt=""
                />
                <Icon
                  v-if="type != 3"
                  size="20"
                  @click="delItems( )"
                  class="delete-img"
                  type="ios-close-circle"
                />
              </div>
              <div class="add-items" v-if="type != 3&&!info.img_url">
                <div class="item">
                  <Icon size="50" type="ios-add" />
                </div>
                <span>支持jpg/png格式</span>
                <input
                  @change="changeIpt($event, info.img_url)"
                  type="file"
                  class="ipt"
                />
              </div>
            </div>
          </div>
          <!-- <Button type="primary"
                  style="margin-right:10px;"
                  ghost>上传附件</Button> -->
          <!-- <Upload style="display: inline"
                  name="your_file"
                  :show-upload-list="false"
                  :headers="headers"
                  multiple
                  :data="uploadData"
                  :on-error="uploadError"
                  :on-progress="onProgress"
                  :on-success="uploadSuccess"
                  :action="$store.state.ip + '/api/deep_img_import'">
            <Button type="primary"
                    style="margin-right: 10px">上传附件</Button>
          </Upload> -->
        </FormItem>
      <FormItem label="安全库存" v-show="isShowInfoMinStock" prop="stock">
        <Input
          type="number"
          :disabled="type == 3 ? true : false"
          v-model="info.warning_number"
          placeholder="请输入库存"
        />
      </FormItem>
      <FormItem label="最高库存" v-show="isShowInfoTopNumber" prop="stock">
        <Input
          type="number"
          :disabled="type == 3 ? true : false"
          v-model="info.top_number"
          placeholder="请输入库存"
        />
      </FormItem>
      <FormItem label="单价(元)" v-show="isShowInfoPrice" prop="price">
        <Input
          type="number"
          :disabled="type == 3 ? true : false"
          v-model="info.price"
          placeholder="请输入金额"
        />
      </FormItem>
    </Form>
    <div class="page-edit" v-show="isShowDetail" style="padding-bottom:100px;">
      <div class="items" v-for="(rows, key) in info.detail" :key="key">
        <!-- id  1 木板   2 木皮   3 实木   4 辅料   5 五金   6 油漆  -->
        <Form ref="item_detail" inline :model="rows" :rules="itemRules">
          <FormItem label="高" prop="long" v-show="isShowDetailLong">
            <Input
              :disabled="type == 3 ? true : false"
              v-model="rows.long"
              placeholder="请输入高度"
            />
          </FormItem>
          <FormItem label="宽" prop="width" v-show="isShowDetailWidth">
            <Input
              :disabled="type == 3 ? true : false"
              v-model="rows.width"
              placeholder="请输入宽度"
            />
          </FormItem>
          <FormItem label="损耗(%)">
            <Input
              type="number"
              :disabled="type == 3 ? true : false"
              v-model="rows.scale"
              placeholder="请输入百分比"
            />
          </FormItem>
          <FormItem label="价格计算方式" prop="todo" v-show="isShowDetailCalc">
            <Select
              filterable
              clearable
              style="width:186px;"
              v-model="rows.todo"
              placeholder="请选择"
            >
              <Option
                v-for="item of priceMathList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></Option>
            </Select>
          </FormItem>
          <FormItem label="安全库存">
            <Input
              type="number"
              :disabled="type == 3 ? true : false"
              v-model="rows.warning_number"
              placeholder="请输入库存"
            />
          </FormItem>
          <FormItem label="最高库存">
            <Input
              type="number"
              :disabled="type == 3 ? true : false"
              v-model="rows.top_number"
              placeholder="请输入库存"
            />
          </FormItem>
          <FormItem label="单价(元)" prop="price">
            <Input
              type="number"
              :disabled="type == 3 ? true : false"
              v-model="rows.price"
              placeholder="请输入金额"
            />
          </FormItem>  
         
          <FormItem label="操作" v-if="isShowDetailBtn">
            <div
              style="width:100%;display:flex;height:100%;align-items:center;"
            >
              <Button
                type="success"
                ghost
                :disabled="type == 3 ? true : false"
                @click="addMaterrial(info.detail)"
                >添加</Button
              >
              <Button
                type="error"
                ghost
                v-if="info.detail.length != 1 && type != 3"
                style="margin-left:10px;"
                @click="removeChild(info.detail, key)"
                >删除</Button
              >
            </div>
          </FormItem>
         
        </Form>
      </div>
    </div>
    <Modal
      v-model="showKey"
      :width="1250"
      :mask-closable="false"
      :closable="false"
    >
      <div>
        <KeyBoard @cancel="successKey" @success="successKey" class="key-co" />
      </div>
      <div slot="footer"></div>
    </Modal>
  </div>
</template>

<script>
import KeyBoard from "../../components/keyboard/index";
export default {
  data() {
    return {
      type: 1,
      info: {
        m_id: "",
        img_url:'',
        abbreviation_title:'',
        detail: [
          {
            long: "",
            width: "",
            price: "",
            stock: "",
            warning_number: "",
            scale: "",
          },
        ],
      },
      id: null,
      materialList: [],
      priceMathList: [
        { label: "按米", value: 1 },
        { label: "按数量", value: 2 },
      ],
      showKey: false,
      itemRules: {
        price: [{ required: true, message: " " }],
        long: [{ required: true, message: " ", trigger: "blur" }],
        width: [{ required: true, message: " ", trigger: "blur" }],
        stock: [{ required: true, message: " " }],
        scale: [{ required: true, message: " " }],
        warning_number: [{ required: true, message: " " }],
      },
      rules: {
        title: [{ required: true, message: " ", trigger: "blur" }],
        m_id: [{ required: true, message: " " }],
        high: [{ required: true, message: " ", trigger: "blur" }],
        unit: [{ required: true, message: " ", trigger: "blur" }],
      },
      basic_type_id: "",
      isShowInfoMinStock: false,
      isShowInfoTopNumber: false,
      isShowInfoHigh: false,
      isShowInfoPrice: false,
      isShowDetail: false,
      isShowDetailLong: false,
      isShowDetailWidth: false,
      isShowDetailCalc: false,
      isShowDetailBtn: false,
    };
  },
  components: { KeyBoard },
  created() {},
  mounted() {
    this.type = this.$route.query.type;
    this.id = this.$route.query.id || "";
    this.type == 1
      ? (this.info.m_id = this.$route.query.back_id * 1)
      : this.info.m_id;
    this.axios("/api/basics_material_index").then((res) => {
      this.materialList = res.data.data;
      console.log(res)
    });
    if (this.id) {
      this.getData(this.id);
    }
    //根据基本类型展示不同字段
    setTimeout(() => {
      let id = this.$route.query.back_id;
      let tempArr = this.$store.state.navgationData[9].sub;
      this.$store.state.navgationData.forEach((element) => {
        if (element.title == "物料档案") {
          element.sub.forEach((elem) => {
            if (elem.id == id) {
              this.basic_type_id = elem.sub_type_id;
            }
          });
        }
      });
      // tempArr.forEach(el => {
      //   console.log('el :>> ', el);
      //   if (el.id == id) {
      //     this.basic_type_id = el.sub_type_id
      //   }
      // });
      switch (this.basic_type_id) {
        // 1木板 2木皮 3实木 4辅料 5五金 6油漆
        case 1:
        case 3:
          this.isShowInfoHigh = true;
          this.isShowDetailLong = true;
          this.isShowDetailWidth = true;
          this.isShowDetail = true;
          this.isShowDetailBtn = true;
          break;
        case 2:
          this.isShowInfoHigh = true;
          this.isShowInfoMinStock = true;
          this.isShowInfoTopNumber = true;
          this.isShowInfoPrice = true;
          break;
        case 4:
        case 5:
        case 6:
          this.isShowInfoMinStock = true;
          this.isShowInfoTopNumber = true;
          this.isShowInfoPrice = true;
          break;
      }
    }, 500);
  },
  computed: {
    setTip() {
      const { type } = this.$route.query;
      const inner =
        type == 1
          ? "新增物料"
          : type == 2
          ? "编辑物料"
          : type == 3
          ? "查看物料"
          : "拷贝物料";
      return inner;
    },
  },
  methods: {
     looks(img) {
      const array = [{ img_url: img }];
      this.$previewImg({
        list: array,
        baseUrl: this.$store.state.ip,
        baseImgField: "img_url",
        baseTitleField: "",
      });
    },
 delItems() {
      this.info.img_url = '';
      this.$forceUpdate();
    },
 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;
    },
     postImg(file, row) {
      let formData = new FormData();
      formData.append("file", file);
      this.axios.post("/api/upload_pic", formData).then((res) => {
        this.info.img_url = res.data.url;
        this.$forceUpdate();
      });
    },
    getData(id) {
      this.axios("/api/material", { params: { id: id } }).then((res) => {
        console.log(res)
        let data = res.data.shift();
        this.info = data;
        if (this.info.detail.length < 1) {
          this.info.detail = [
            {
              long: "",
              width: "",
              price: "",
              stock: "",
              warning_number: "",
              scale: "",
            },
          ];
        }
      });
    },
    postData() {
      const { type } = this.$route.query;
      this.info.op = type == 1 || type == 4 ? "add" : "edit";
      [2, 4, 5, 6].includes(this.basic_type_id) &&
        ((this.info.detail[0].top_number = this.info.top_number),
        (this.info.detail[0].warning_number = this.info.warning_number),
        (this.info.detail[0].price = this.info.price));
      type == 4 ? (this.info.id = "") : "";
      this.axios.post("/api/material", this.info).then((res) => {
        console.log(this.info)
        if (res.code == 200) {
          this.$Message.success(res.msg);
          this.back();
        }
      });
    },
    back() {
      this.$router.go(-1);
    },
    successKey(str) {
      this.info.formula = str;
      this.showKey = false;
    },
    popKeyBoard() {
      this.showKey = true;
    },
    async handleSubmit(name, itemName) {
      // const nameValue = await this.$refs[name].validate((valid)=>valid)
      // let result = []
      // for(let i = 0;i<this.$refs[itemName].length;i++){
      //     this.$refs[itemName][i].validate(valid=>{
      //         result.push(valid)
      //     })
      // }
      // const itemVal = result.every(val=>val)
      // if(nameValue&&itemVal){
      this.postData();
      // }
    },
    addMaterrial(row) {
      row.push({
        long: "",
        width: "",
        price: "",
        stock: "",
        warning_number: "",
        scale: "",
      });
    },
    removeChild(row, n) {
      row.splice(n, 1);
    },
  },
};
</script>

<style lang="scss" scoped>
.items {
  padding: 10px;
  box-shadow: 0 2px 7px rgba(0, 0, 0, 0.15);
  border-color: transparent;
  position: relative;
  margin: 20px 0;
}
.product-img {
  padding-top: 10px;
}
.product-add {
  padding: 10px 0;
  // display: flex;
  flex-wrap: nowrap;
  .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;
    }
  }
  .img_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: 0px;
  top: 0px;
  color: red;
}
</style>
