<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 style="display:flex;flex-wrap:wrap" ref="Info" :model="info" :rules="rules" :label-width='120'>
        <FormItem label="部件分类名称" prop="p_id" style="width:300px">
          <Select v-if="type != 3" filterable clearable v-model="info.p_id">
            <Option
              v-for="item of partList"
              :key="item.id"
              :value="item.id"
              :label="item.title"
            ></Option>
          </Select>
          <span v-else>{{
            partList.length > 0 && info.p_id
              ? partList.filter((item) => item.id == info.p_id)[0].title
              : ""
          }}</span>
        </FormItem>
        <FormItem label="标签" prop="label" style="width:300px">
          <RadioGroup v-model="info.label" style="width:100%;" @on-change='onChange'>
            <Radio :disabled="type == 3" :label='1'>是</Radio>
            <Radio :disabled="type == 3" :label='0'>否</Radio>
          </RadioGroup>
        </FormItem>
         <FormItem label="打印格式" prop="format" style="width:300px">
          <Select v-if="type != 3" filterable clearable v-model="info.format" @on-change='selectOnChange'>
            <Option
              v-for="item of formatList"
              :key="item.id"
              :value="item.id"
              :label="item.title"
            ></Option>
          </Select>
          <span v-else>{{info.format==0?'不打印':info.format==1?'芯片+标签':info.format==2?'芯片':'标签'}}</span>
        </FormItem>
        <FormItem label="部件名称" prop="title" style="width:300px">
          <Input
            v-if="type != 3"
            v-model="info.title"
            placeholder="请输入部件名称"
          />
          <span v-else>{{ info.title }}</span>
        </FormItem>
        <FormItem label="单位" prop="company" style="width:300px">
          <Input
            v-if="type != 3"
            v-model="info.company"
            placeholder="请输入单位"
          />
          <span v-else>{{ info.company }}</span>
        </FormItem>
        <FormItem label="关联产品分类" prop="p_id">
          <div style="display:flex;align-items:center;width:100%;">
            <Dropdown v-if="type != 3">
              <Button :disabled="type == 3" type="primary" ghost
                >选择产品</Button
              >
              <DropdownMenu slot="list">
                <Downtree
                  @childByValue="handleClick"
                  :parent="productTypes"
                ></Downtree>
              </DropdownMenu>
            </Dropdown>

            <Button style="margin-left:20px;" v-if="nowSelectObj.title">{{
              nowSelectObj.title || ""
            }}</Button>
          </div>
        </FormItem>
      </Form>
      <div class="edit-table-log">
        <div>
          <span>零部件添加：</span>
          <Button
            v-if="type != 3"
            size="small"
            @click="addZeroPart"
            type="primary"
            ghost
            >新增木板</Button
          >
        </div>
        <span class="footer-log"
          >备注:适用于 ＋(加) -(减) ×(乘)
          ÷(除)不输入就是不设定公式，支持单项输入)</span
        >
      </div>
      <Table
        stripe
        border
        tooltip
        :columns="tableColums"
        :data="tableData"
        :width="tableWidth"
      >
        <template slot-scope="{ index }" slot="spare_parts">
          <Input
            v-if="type != 3"
            placeholder="请输入零部件名称"
            v-model="tableData[index].spare_parts"
          />
          <span v-else>{{ tableData[index].spare_parts }}</span>
        </template>
        <template slot-scope="{ index }" slot="title">
          <div>
            <Select
              filterable
              clearable
              v-if="type != 3"
              label-in-value
              @on-change="changeSe($event, index)"
              v-model="tableData[index].material_id"
            >
              <Option
                :data-unit="item.unit"
                :tag="item.high"
                v-for="item of materialWoodList"
                :key="item.id"
                :value="item.id"
                :label="item.title"
              ></Option>
            </Select>
            <span v-else>{{
              materialWoodList.length > 0 && tableData[index].material_id
                ? materialWoodList.filter(
                    (item) => item.id == tableData[index].material_id
                  )[0].title
                : ""
            }}</span>
          </div>
        </template>
        <template slot-scope="{ index }" slot="number">
          <Input
            v-if="type != 3"
            placeholder="请输入数量"
            v-model="tableData[index].number"
          />
          <span v-else>{{ tableData[index].number }}</span>
        </template>
        <template slot-scope="{ index }" slot="company">
          <!-- <Input
            placeholder="请输入单位"
            disabled
            v-model="tableData[index].company"
          /> -->
          <span>{{ tableData[index].company }}</span>
        </template>
        <template slot-scope="{ index }" slot="long">
          <Input
            v-if="type != 3"
            @on-focus="openKey(index, 'long')"
            placeholder="请输入高"
            v-model="tableData[index].long"
          />
          <span v-else>{{ tableData[index].long }}</span>
        </template>
        <template slot-scope="{ index }" slot="wide">
          <Input
            v-if="type != 3"
            @on-focus="openKey(index, 'wide')"
            placeholder="请输入宽"
            v-model="tableData[index].wide"
          />
          <span v-else>{{ tableData[index].wide }}</span>
        </template>
        <template slot-scope="{ index }" slot="thick">
          <!-- <Input
            disabled
            placeholder="自动生成"
            v-model="tableData[index].thick"
          /> -->
          <span>{{ tableData[index].thick }}</span>
        </template>
        <template slot-scope="{ index }" slot="requirement">
          <Select
            v-if="type != 3"
            placeholder="请选择工艺要求"
            v-model="tableData[index].technological_requirement_id"
          >
            <Option
              v-for="item in processRequireList"
              :key="item.id"
              :value="item.id"
              :label="item.title"
            ></Option>
          </Select>
          <span v-else>{{
            processRequireList.length > 0 &&
            tableData[index].technological_requirement_id
              ? processRequireList.filter(
                  (item) =>
                    item.id == tableData[index].technological_requirement_id
                )[0].title
              : ""
          }}</span>
        </template>
        <template slot-scope="{ index }" slot="sub_num">
          <Select v-if="type != 3" v-model="tableData[index].sub_num">
            <Option :value="0" label="0"></Option>
            <Option :value="1" label="1"></Option>
            <Option :value="2" label="2"></Option>
          </Select>
          <span v-else>{{
            tableData[index].sub_num == 0
              ? 0
              : tableData[index].sub_num == 1
              ? 1
              : 2
          }}</span>
        </template>
        <template slot-scope="{ index }" slot="woodSkinSet">
          <Select v-if="type != 3" v-model="tableData[index].veneer_id">
            <Option
              v-for="item in materialWoodSkinList"
              :key="item.id"
              :value="item.id"
              :label="item.title"
            ></Option>
          </Select>
          <span v-else>{{
            materialWoodSkinList.length > 0 && tableData[index].veneer_id
              ? materialWoodSkinList.filter(
                  (item) => item.id == tableData[index].veneer_id
                )[0].title
              : ""
          }}</span>
        </template>
        <template slot-scope="{ index }" slot="paintSet">
          <Select v-if="type != 3" v-model="tableData[index].paint_id">
            <Option
              v-for="item in materialPaintList"
              :key="item.id"
              :value="item.id"
              :label="item.title"
            ></Option>
          </Select>
          <span v-else>{{
            materialPaintList.length > 0 && tableData[index].paint_id
              ? materialPaintList.filter(
                  (item) => item.id == tableData[index].paint_id
                )[0].title
              : ""
          }}</span>
        </template>
         <template slot-scope="{ row,index }" slot="label">
          <Select v-if="type != 3" v-model="tableData[index].label" @on-change='tableLabelchange(row,index)'>
            <Option
              v-for="item in label"
              :key="item.id"
              :value="item.id"
              :label="item.title"
            ></Option>
          </Select>
          <span v-else>{{row.label==1?'是':'否'}}</span>
        </template>
         <template slot-scope="{ row,index }" slot="format">
          <Select v-if="type != 3" v-model="tableData[index].format" @on-change="tableformatchange($event,index)">
            <Option
              v-for="item in formatList"
              :key="item.id"
              :value="item.id"
              :label="item.title"
            ></Option>
          </Select>
          <span v-else>{{row.format==0?'否':row.format==1?'芯片+标签':row.format==2?'芯片':'标签'}}</span>
        </template>
        <template slot="printNum" slot-scope="{ index }">
          <Input
            placeholder="请输入打印数量"
            v-if="type != 3"
            v-model="tableData[index].print_num"
          />
          <span v-else>{{ tableData[index].print_num }}</span>
        </template>
        <template slot-scope="{ index }" slot="set">
          <div style="display:Flex;justify-content:space-around">
            <Button
              v-if="type != 3"
              size="small"
              type="primary"
              @click="copyParts(tableData, index)"
              >复制</Button
            >
            <Button
              v-if="type != 3"
              size="small"
              type="error"
              @click="delItems(tableData, index)"
              >删除</Button
            >
          </div>
        </template>
      </Table>
      <div class="edit-table-log">
        <div>
          <Button
            v-if="type != 3"
            size="small"
            @click="addMetals"
            type="primary"
            ghost
            >新增五金</Button
          >
        </div>
      </div>
      <Table
        stripe
        border
        :columns="metalsTableColums"
        :data="metalsTableData"
        :width="tableWidth"
      >
        <template slot-scope="{ index }" slot="slot_metals">
          <Select
            v-if="type != 3"
            @on-change="changeSeMetal($event, index)"
            placeholder="请选择"
            v-model="metalsTableData[index].material_id"
          >
            <Option
              v-for="item in metalsList"
              :data-unit="item.unit"
              :key="item.id"
              :value="item.id"
              :label="item.title"
            ></Option>
          </Select>
          <span v-else>{{
            metalsList.length > 0 && metalsTableData[index].material_id
              ? metalsList.filter(
                  (item) => item.id == metalsTableData[index].material_id
                )[0].title
              : ""
          }}</span>
        </template>
        <template slot-scope="{ index }" slot="slot_metals_number">
          <Input
            v-if="type != 3"
            @on-change="handleTotalPriceCalc(metalsTableData[index])"
            placeholder="请输入数量"
            v-model="metalsTableData[index].number"
          />
          <span v-else>{{ metalsTableData[index].number }}</span>
        </template>
        <template slot-scope="{ index }" slot="slot_metals_unit">
          <!-- <Input
            placeholder="请输入单位"
            disabled
            v-model="metalsTableData[index].company"
          /> -->
          <span>{{ metalsTableData[index].company }}</span>
        </template>
        <template slot-scope="{ index }" slot="slot_metals_price">
          <Input
            v-if="type != 3"
            placeholder="请输入单价"
            @on-change="handleTotalPriceCalc(metalsTableData[index])"
            v-model="metalsTableData[index].price"
          />
          <span v-else>{{ metalsTableData[index].price }}</span>
        </template>
        <template slot-scope="{ index }" slot="slot_metals_total_price">
          <Input
            v-if="type != 3"
            placeholder="请输入总价"
            v-model="metalsTableData[index].total_price"
          />
          <span v-else>{{ metalsTableData[index].total_price }}</span>
        </template>
        <template slot-scope="{ index }" slot="slot_metals_set">
          <div style="display:Flex;justify-content:space-around">
            <Button
              v-if="type != 3"
              size="small"
              type="primary"
              @click="copyParts(metalsTableData, index)"
              >复制</Button
            >
            <Button
              v-if="type != 3"
              size="small"
              type="error"
              @click="delItems(metalsTableData, index)"
              >删除</Button
            >
          </div>
        </template>
      </Table>
    </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>
</template>

<script>
import KeyBoard from "../../components/keyboard/index";
import Downtree from "../../components/drowDown/index";
export default {
  data() {
    return {
      type: 1,
      id: null,
      tableWidth: null,
      info: {
        company: "",
        p_id: "",
        bp_id: null,
        label: 1,
        title: "",
        format:1
      },
      partList: [],
      partsData: [],
      label:[{title:'是',id:1},{title:'否',id:0}],
      tableColums: [
        {
          title: "零部件名称",
          align: "center",
          key: "spare_parts",
          slot: "spare_parts",
          resizable: true,
          width: 150,
          fixed: "left",
        },
        {
          title: "物料名称",
          align: "center",
          key: "title",
          slot: "title",
           resizable: true,
          width: 150,
        },
        {
          title: "数量",
          align: "center",
          key: "number",
          slot: "number",
           resizable: true,
          width: 150,
        },
        {
          title: "单位",
          align: "center",
          key: "company",
          slot: "company",
           resizable: true,
          width: 150,
        },
        {
          title: "高",
          align: "center",
          key: "long",
          slot: "long",
          resizable: true,
          width: 150,
        },
        {
          title: "宽",
          align: "center",
          key: "wide",
          slot: "wide",
          resizable: true,
          width: 150,
        },
        {
          title: "厚",
          align: "center",
          key: "thick",
          slot: "thick",
          minWidth: 120,
        },
        {
          title: "工艺要求",
          align: "center",
          key: "requirement",
          slot: "requirement",
           resizable: true,
          width: 150,
        },
        {
          title: "贴木皮名称",
          align: "center",
          key: "num",
          slot: "woodSkinSet",
          resizable: true,
          width: 150,
        },
        {
          title: "贴面数",
          align: "center",
          key: "sub_num",
          slot: "sub_num",
          resizable: true,
          width: 150,
        },
        {
          title: "油漆组合",
          align: "center",
          key: "paint",
          slot: "paintSet",
           resizable: true,
          width: 150,
        },
         {
          title: "是否生成芯片码",
          align: "center",
          key: "label",
          slot: "label",
          resizable: true,
          width: 150,
        },
         {
          title: "打印格式",
          align: "center",
          key: "format",
          slot: "format",
           resizable: true,
          width: 150,
        },
        {
          title: "打印数量",
          align: "center",
          key: "printNum",
          slot: "printNum",
          resizable: true,
          width: 150,
        },
        {
          title: "操作",
          align: "center",
          slot: "set",
          minWidth: 200,
          fixed: "right",
        },
      ],
      metalsTableColums: [
        {
          title: "五金",
          align: "center",
          key: "spare_parts",
          slot: "slot_metals",
          resizable: true,
          width: 260,
        },
        {
          title: "数量",
          align: "center",
          key: "number",
          slot: "slot_metals_number",
          resizable: true,
          width: 260,
        },
        {
          title: "单位",
          align: "center",
          key: "unit",
          slot: "slot_metals_unit",
          resizable: true,
          width: 260,
        },
        {
          title: "单价",
          align: "center",
          key: "price",
          slot: "slot_metals_price",
          resizable: true,
          width: 260,
        },
        {
          title: "总价",
          align: "center",
          key: "total_prive",
          slot: "slot_metals_total_price",
           resizable: true,
          width: 260,
        },
        {
          title: "操作",
          align: "center",
          slot: "slot_metals_set",
          minWidth: 200,
        }
      ],
      tableData: [],
      metalsTableData: [],
      rules: {
        p_id: [{ required: true, message: " " }],
        label: [{ required: true, message: "请选择标签" }],
        title: [{ required: true, message: " ", trigger: "blur" }],
        company: [{ required: true, message: " ", trigger: "blur" }],
        format: [{ required: true, message: " " }],
      },
      formatList:[{title:'芯片+标签',id:1},{title:'芯片',id:2},{title:'标签',id:3},{title:'否',id:0}],
      addObj: {
        title: "",
        number: "",
        company: "",
        spare_parts: "",
        long: "",
        wide: "",
        thick: "",
        requirement: "",
        label: 1,
        format:1,
        p_id: null,
      },
      zeroParts: [],
      showKey: false,
      attrindex: null,
      attrName: "",
      measureList: [
        { e_title: "H", title: "高", id: 1, sort: 0 },
        { e_title: "W", title: "宽", id: 1, sort: 0 },
        { e_title: "D", title: "深", id: 1, sort: 0 },
      ],
      productTypes: [],
      nowSelectObj: {},
      // 木板列表
      materialWoodList: [],
      // 木皮列表
      materialWoodSkinList: [],
      // 油漆列表
      materialPaintList: [],
      // 工艺要求列表
      processRequireList: [],
      // 饰面列表
      faceList: [],
      // 五金列表
      metalsList: [],
    };
  },
  mounted() {
    this.getProductTypes();
    this.getPartsData();
    this.type = this.$route.query.type;
    this.id = this.$route.query.id;
    if (this.id) {
      this.getDetails(this.id);
    }
    this.getParts();
    this.tableWidth = window.innerWidth - 350;
    window.addEventListener(
      "resize",
      (e) => (this.tableWidth = e.target.innerWidth - 350)
    );
    this.axios("/api/material", { params: { sub_type_id: 1 } }).then((res) => {
      this.materialWoodList = res.data.data;
    });
    this.axios("/api/material", { params: { sub_type_id: 2 } }).then((res) => {
      this.materialWoodSkinList = res.data.data;
    });
    this.axios("/api/material_combination").then((res) => {
      this.materialPaintList = res.data.data;
    });
    this.axios("/api/properties_index", { params: { id: 1 } }).then((res) => {
      this.faceList = res.data.data;
    });
    this.axios("/api/material", { params: { sub_type_id: 5 } }).then((res) => {
      this.metalsList = res.data.data;
    });
    this.axios("/api/technological_requirement").then((res) => {
      this.processRequireList = res.data.data;
    });
  },
  components: {
    KeyBoard,
    Downtree,
  },
  computed: {
    setTip() {
      const { type } = this.$route.query;
      const inner =
        type == 1
          ? "新增部件"
          : type == 2
          ? "编辑部件"
          : type == 3
          ? "查看部件"
          : "拷贝部件";
      return inner;
    },
  },
  methods: {
    tableformatchange(e,index){
       if(e==0){
         this.tableData[index].label=0
       }
    },
    tableLabelchange(row,index){
          if(row.label == 1){
             this.tableData[index].format = 0
          }
    },
    selectOnChange(val){
       if(val==0){
         this.info.label = 0
       }
    },
    onChange(val){
      if(val == 0){
        this.info.format = 0
      }
    },
    back() {
      this.$router.push({ name: "PartsManageHome" });
    },
    getPartsData() {
      this.axios("/api/material").then((res) => {
        this.zeroParts = res.data.data;
      });
    },
    getParts() {
      this.axios("/api/basics_parts_index").then((res) => {
        this.partList = res.data.data;
      });
    },
    postData() {
      const { type } = this.$route.query;
      if (!this.info.bp_id) {
        return this.$Message.warning("请关联产品");
      }
      let postInfo = JSON.parse(JSON.stringify(this.info)),
        sendData = { top: {} };
      sendData.op = type == 1 || type == 4 ? "add" : "edit";
      type == 4 ? (sendData.id = "") : "";
      for (let i in postInfo) {
        i == "detail"
          ? (sendData.detail = postInfo["detail"])
          : (sendData.top[i] = postInfo[i]);
      }
      sendData.detail = [...this.tableData, ...this.metalsTableData];
      this.axios.post("/api/parts_save", sendData).then((res) => {
        if (res.code == 200) {
          this.$Message.success(res.msg);
          this.back();
        }
      });
    },
    getDetails(id) {
      this.axios("/api/parts_detail", { params: { id: id } }).then((res) => {
        this.info = res.data;
        this.info.bp_id
          ? this.axios("/api/basics_product_list", {
              params: { id: this.info.bp_id },
            }).then((res) => {
              this.measureList = res.data[0].measure;
            })
          : "";
        // this.tableData = res.data.detail;
        // 1 木板  2 木皮  3 实木  4 辅料  5 五金  6 油漆
        res.data.detail.forEach((element) => {
          if (element.type_id == 2 || element.type_id == 1) {
            this.tableData.push(element);
          } else if (element.type_id == 5) {
            element.total_price = element.price * 1 * element.number;
            this.metalsTableData.push(element);
          }
        });
        if (this.info.product) {
          this.nowSelectObj = this.info.product;
        }
        this.$route.params.info
          ? this.tableData.push(this.$route.params.info)
          : "";
      });
    },
    addNewsPart() {
      this.$router.push({
        name: "PageEdit",
        params: {
          list: this.list,
          title: this.tableData.length >= 1 ? "编辑零部件" : "新增零部件",
          type: "零部件",
        },
      });
    },
    delItems(row, n) {
      row.splice(n, 1);
    },
    addZeroPart() {
      let add = JSON.parse(JSON.stringify(this.addObj));
      add.sub_num = 0;
      this.tableData.push(add);
    },
    addMetals() {
      let add = JSON.parse(JSON.stringify(this.addObj));
      this.metalsTableData.push(add);
    },
    changeSe(e, n) {
      let event = window.event;
      let unit = event.target.dataset.unit;
      this.tableData[n].company = unit ? unit : "";
      this.tableData[n].thick = e.tag;
      this.tableData[n].title = e.title;
    },
    changeSeMetal(e, n) {
      let event = window.event;
      let unit = event.target.dataset.unit;
      this.metalsTableData[n].company = unit ? unit : "";
    },
    handleSubmit(name) {
      this.$refs[name].validate((valid) => {
        console.log(valid)
        if (valid) {
          this.postData();
        }
      });
    },
    successKey(str) {
      this.tableData[this.attrindex][this.attrName] = str;
      this.showKey = false;
    },
    cancelKey() {
      this.showKey = false;
    },
    openKey(row, attr) {
      this.showKey = true;
      this.attrindex = row;
      this.attrName = attr;
    },
    getProductTypes(e) {
      this.axios("/api/parts_product_list", { params: { id: e } }).then(
        (res) => {
          if (res.code == 200) {
            this.productTypes = res.data;
          }
        }
      );
    },
    handleClick(e) {
      let data = JSON.parse(e);
      this.nowSelectObj = data;
      this.info.bp_id = this.nowSelectObj.id;
      this.axios("/api/basics_product_list", {
        params: { id: this.info.bp_id },
      }).then((res) => {
        this.measureList = res.data[0].measure;
      });
    },
    copyParts(array, n) {
      let copy_data = JSON.parse(JSON.stringify(array[n]));
      copy_data.id = "";
      array.splice(n, 0, copy_data);
    },
    handleTotalPriceCalc(row) {
      row.total_price = row.number * 1 * row.price || 0;
    },
  },
};
</script>

<style lang="scss" scoped>
.edit-table-log {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 10px;
  padding-top: 20px;
  .footer-log {
    color: #666666;
  }
}
.page-edit {
  overflow: hidden;
  overflow-y: auto;
  position: relative;
  top: 20px;
  height: 80%;
}
/deep/ .ivu-table-wrapper {
  overflow: visible;
  color: red;
} //穿透iview
/deep/ .ivu-select-dropdown-list {
  z-index: 10000;
}
/deep/.ivu-form-item-content {
  span {
    vertical-align: middle;
  }
}
</style>
