<template>
  <div>
    <FullPage
      :title="$route.query.title"
      :list="list"
      @init="init"
      :loading="loading"
      @searchData="init"
      @changePage="changePage"
      @changeSize="changeSize"
      :tableColums="tableColums"
      :tableData="tableData"
      :pageIndex="pageIndex"
      :total="total"
    >
      <div slot="titleButton" style="display:flex;">
        <Upload
          v-if="persimissionData['批量导入'] || persimissionData.all"
          name="your_file"
          :show-upload-list="false"
          :headers="headers"
          :on-error="uploadError"
          :on-success="uploadSuccess"
          :action="$store.state.ip + '/api/product_import'"
        >
          <Button type="success" ghost icon="md-exit" style="margin-right:10px;"
            >批量导入</Button
          >
        </Upload>
        <Button
          v-if="persimissionData['批量导出'] || persimissionData.all"
          @click="exportData"
          type="warning"
          ghost
          icon="md-return-left"
          style="margin-right:10px;"
          >批量导出</Button
        >
        <!-- v-if="persimissionData['批改替换项'] || persimissionData.all" -->
        <Button
          type="primary"
          ghost
          @click="showModal = true"
          style="margin-right:10px;"
          >批改替换项</Button
        >
        <Button
          v-if="persimissionData['新增产品'] || persimissionData.all"
          type="primary"
          ghost
          icon="md-add"
          @click="goPage(1)"
          >新增产品</Button
        >
      </div>
      <div slot="navButton"></div>
      <template slot="set" slot-scope="{ row }">
        <div class="table-set">
          <svg
            style="font-size:20px"
            color="#3764FF"
            @click="goPage(4, row)"
            class="icon icon-nav"
            aria-hidden="true"
          >
            <use xlink:href="#iconcopy-01"></use>
          </svg>
          <svg
            v-if="persimissionData['编辑'] || persimissionData.all"
            style="font-size:20px"
            color="#3764FF"
            @click="goPage(2, row)"
            class="icon icon-nav"
            aria-hidden="true"
          >
            <use xlink:href="#iconbianji"></use>
          </svg>
          <svg
            style="font-size:20px"
            color="green"
            @click="goPage(3, row)"
            class="icon icon-nav"
            aria-hidden="true"
          >
            <use xlink:href="#iconxiangqing"></use>
          </svg>

          <svg
            v-if="persimissionData['删除'] || persimissionData.all"
            @click="delItems(row)"
            class="icon icon-nav"
            style="font-size:20px"
            color="red"
            aria-hidden="true"
          >
            <use xlink:href="#iconshanchu"></use>
          </svg>
        </div>
      </template>
    </FullPage>
    <Modal
      v-model="showModal"
      :title="'批改替换项:' + $route.query.title"
      width="1300"
    >
      <div class="show_modal_content">
        <div class="show_modal_content_left">
          <div class="show_modal_content_left_item">
            <div class="show_modal_content_left_item_title">
              <Button
                type="primary"
                style="cursor:default;border-radius:0"
                :ghost="!isSelectAll"
                @click="handleProductAllClick(tableData)"
                >产品名称</Button
              >
            </div>
            <div class="show_modal_content_left_item_detail_warp">
              <div
                class="show_modal_content_left_item_detail"
                v-for="product in tableData"
                :key="product.id"
              >
                <Button
                  type="primary"
                  :ghost="!product.isSelect"
                  style="border-radius:10px"
                  @click="handleProductClick(product, 2)"
                  >{{ product.title }}</Button
                >
              </div>
            </div>
          </div>
          <div class="show_modal_content_left_item">
            <div class="show_modal_content_left_item_title">
              <Button
                type="primary"
                style="cursor:default;border-radius:0"
                ghost
                >部件名称</Button
              >
            </div>
            <div v-if="productPartList.length < 1">
              <Button type="primary" ghost style="border-radius:10px"
                >无</Button
              >
            </div>
            <div v-else class="show_modal_content_left_item_detail_warp">
              <div
                class="show_modal_content_left_item_detail"
                v-for="part in productPartList"
                :key="part.id"
              >
                <Button
                  type="primary"
                  :ghost="!part.isSelect"
                  style="border-radius:10px"
                  @click="handlePartClick(part, 3)"
                  >{{ part.title }}</Button
                >
              </div>
            </div>
          </div>
        </div>
        <div class="show_modal_content_right">
          <div class="show_modal_content_right_top">
            <Button type="primary" @click="handleAddChangeable"
              >新增替换部件</Button
            >
          </div>
          <div class="show_modal_content_right_body">
            <Table
              border
              max-height="500"
              :columns="changeableColumns"
              :data="changeableTableData"
            ></Table>
          </div>
        </div>
      </div>
      <div slot="footer">
        <Button
          type="primary"
          style="margin-right:10px;"
          @click="showModal = false"
          >取消</Button
        >
        <Button
          type="primary"
          style="margin-right:10px;"
          @click="handleChangeableConfirm"
          >确定</Button
        >
      </div>
    </Modal>
    <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 { mapState } from "vuex";
import KeyBoard from "../../components/keyboard/index";
export default {
  components: { KeyBoard },
  data() {
    return {
      list: [
        {
          title: "产品名称",
          name: "Input",
          value: "",
          serverName: "title",
          placeholder: "请输入产品名称",
        },
        {
          title: "产品型号",
          name: "Input",
          value: "",
          serverName: "model",
          placeholder: "请输入产品型号",
        },
        {
          title: "图号",
          name: "Input",
          value: "",
          serverName: "url_number",
          placeholder: "请输入图号",
        },
      ],
      tableColums: [
        {
          title: "序号",
          type: "index",
          align: "center",
          key: "",
          width: "100",
        },
        { title: "分类名称", align: "center", key: "type_name" },
        { title: "产品名称", align: "center", key: "title" },
        { title: "计量单位", align: "center", key: "unit" },
        { title: "型号", align: "center", key: "model" },
        { title: "图号", align: "center", key: "url_number" },
        {
          title: "产品图片",
          align: "center",
          key: "company",
          render: (h, params) => {
            const { row } = params;
            return h("img", {
              attrs: {
                src: this.$store.state.ip + params.row.img_url,
                style:
                  "max-width:50px;max-height:50px;position:relative;top:3px;",
              },
              on: {
                click: (e) => {
                  this.axios("/api/orders_img", {
                    params: { id: row.id, type: 0 },
                  }).then((res) => {
                    console.log(
                      "this.$store.state.ip :>> ",
                      this.$store.state.ip
                    );
                    if (res.code == 200) {
                      row.imgs = res.data;
                      this.$previewImg({
                        list: res.data,
                        baseUrl: this.$store.state.ip,
                        baseImgField: "img_url",
                        baseTitleField: "",
                      });
                    }
                  });
                  // if(row.imgs&&row.imgs.length>0){//优化处理考虑到图纸我就暂时不处理了
                  //     this.$previewImg({
                  //         list:row.imgs,
                  //         baseUrl:this.$store.state.ip,
                  //         baseImgField:'img_url',
                  //         baseTitleField:''
                  //     })
                  // }else{
                  //     this.axios('/api/orders_img',{params:{id:row.id,type:0}}).then(res=>{
                  //         if(res.code == 200){
                  //             row.imgs = res.data
                  //             this.$previewImg({
                  //                 list:row.imgs,
                  //                 baseUrl:this.$store.state.ip,
                  //                 baseImgField:'img_url',
                  //                 baseTitleField:''
                  //             })
                  //         }
                  //     })
                  // }
                },
              },
            });
          },
        },
        {
          title: "图纸",
          align: "center",
          key: "url",
          render: (h, params) => {
            const { row } = params;
            return h("img", {
              attrs: {
                src: this.$store.state.ip + params.row.url,
                style:
                  "max-width:50px;max-height:50px;position:relative;top:3px;",
              },
              on: {
                click: (e) => {
                  this.axios("/api/orders_img", {
                    params: { id: row.id, type: 1 },
                  }).then((res) => {
                    if (res.code == 200) {
                      row.imgs = res.data;
                      this.$previewImg({
                        list: row.imgs,
                        baseUrl: this.$store.state.ip,
                        baseImgField: "img_url",
                        baseTitleField: "",
                      });
                    }
                  });
                },
              },
            });
          },
        },
        { title: "操作", align: "center", slot: "set", width: "150" },
      ],
      tableData: [],
      pageIndex: 1,
      total: 0,
      pageSize: 10,
      proxyObj: {},
      loading: false,
      headers: { Authorization: localStorage.getItem("token") },
      showModal: false,
      productPartList: [],
      currentProductList: [],
      changeableColumns: [
        {
          title: "替换部件",
          align: "center",
          key: "part_id",
          render: (h, params) => {
            const { index } = params;
            const currencyRow = this.changeableTableData[index];
            return h(
              "Select",
              {
                props: {
                  value: currencyRow.part_id,
                  size: "small",
                  transfer: true,
                  clearable: true,
                  filterable: true,
                },
                on: {
                  "on-change": (e) => {
                    currencyRow.part_id = e;
                  },
                },
              },
              [
                this.partsList.map((item) => {
                  return h("Option", {
                    props: { label: item.title, value: item.id },
                  });
                }),
              ]
            );
          },
        },
        {
          title: "高",
          align: "center",
          key: "formula_l",
          width: "100px",
          render: (h, params) => {
            const { index } = params;
            const currencyRow = this.changeableTableData[index];
            return h("Input", {
              props: {
                placeholder: "请输入高",
                value: currencyRow.formula_l,
                disabled: this.isChecked,
              },
              on: {
                "on-focus": () => {
                  this.openKey(index, "formula_l", currencyRow);
                },
              },
            });
          },
        },
        {
          title: "宽",
          align: "center",
          key: "formula_w",
          width: "100px",
          render: (h, params) => {
            const { index } = params;
            const currencyRow = this.changeableTableData[index];
            return h("Input", {
              props: {
                placeholder: "请输入宽",
                value: currencyRow.formula_w,
              },
              on: {
                "on-focus": () => {
                  this.openKey(index, "formula_w", currencyRow);
                },
              },
            });
          },
        },
        {
          title: "厚",
          align: "center",
          key: "formula_h",
          width: "100px",
          render: (h, params) => {
            const { index } = params;
            const currencyRow = this.changeableTableData[index];
            return h("Input", {
              props: {
                placeholder: "请输入厚",
                value: currencyRow.formula_h,
              },
              on: {
                "on-focus": () => {
                  this.openKey(index, "formula_h", currencyRow);
                },
              },
            });
          },
        },
        {
          title: "操作",
          align: "center",
          key: "set",
          width: "100px",
          render: (h, params) => {
            const { index } = params;
            // const currencyRow = this.changeableTableData[index];
            return h(
              "a",
              {
                on: {
                  click: () => {
                    this.changeableTableData.splice(index, 1);
                  },
                },
              },
              "删除"
            );
          },
        },
      ],
      changeableTableData: [],
      partsList: [],
      showKey: false,
      measureList: [],
      currencyChoose: {},
      attrindex: null,
      attrName: "",
      isSelectAll: false,
    };
  },
  beforeRouteLeave(to, from, next) {
    if (to.path == "/cms/product/edit") {
      this.$route.meta.keepAlive = true;
    } else {
      this.$route.meta.keepAlive = false;
    }
    next();
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.getData(vm.proxyObj);
    });
  },
  created() {
    // 获取部件列表
    this.axios("/api/parts_index").then((res) => {
      this.partsList = res.data.data;
    });
    // 获取产品分类测量字段
    this.axios("/api/basics_product_list", {
      params: { id: this.$route.query.id },
    }).then((res) => {
      if (res.code == 200) {
        const { data } = res;
        const result = data.filter((rows) => rows.id == this.$route.query.id);
        this.measureList = result[0].measure;
      }
    });
  },
  mounted() {
    this.proxyObj.type_id = this.$route.query.id;
    this.getData(this.proxyObj);
  },
  computed: {
    ...mapState(["persimissionData"]),
  },
  watch: {
    "$route.query.title": {
      handler() {
        this.proxyObj.type_id = this.$route.query.id;
        this.list.forEach((element) => {
          element.value = "";
        });
        this.proxyObj.model = "";
        this.proxyObj.title = "";
        this.getData(this.proxyObj);
      },
    },
  },
  methods: {
    init(row) {
      this.pageIndex = 1;
      row.page_index = this.pageIndex;
      row.page_size = this.pageSize;
      row.type_id = this.$route.query.id; //产品管理因为无法使用id 所以用type_id替代
      this.proxyObj = row;
      this.getData(row);
    },
    getData(row) {
      this.loading = true;
      this.axios("/api/product", { params: row }).then((res) => {
        this.loading = false;
        this.tableData = res.data.data;
        this.total = res.data.total;
        this.tableData.map((item) => (item.isSelect = false));
      });
    },
    delItems(row) {
      this.confirmDelete({
        content: "确认删除么？",
        then: () => {
          this.axios
            .post("/api/product", { id: row.id, state: 0 })
            .then((res) => {
              if (res.code == 200) {
                this.$Message.success(res.msg);
                this.getData(this.proxyObj);
              }
            });
        },
      });
    },
    handleProductAllClick(product) {
      this.isSelectAll = !this.isSelectAll;
      // let  flag
      product.map((item) => {
        item.isSelect = this.isSelectAll;
      });
      let ids = product.map((item) => item.id);
      this.isSelectAll &&
        this.axios
          .post("/api/support_product_get_part", {
            type: 2,
            basic_product_id: [this.$route.query.id],
            product_id: ids,
            part_id: [],
          })
          .then((res) => {
            console.log(res);
            this.productPartList = res.data;
            this.productPartList.map((item) => (item.isSelect = false));
          });
    },
    handleProductClick(product, type) {
      product.isSelect = !product.isSelect;
      this.currentProductList = product;
      const temp_product = this.tableData.filter((item) => item.isSelect);
      const product_id = temp_product.map((item) => item.id);
      // 判断是否全选，全选标题选中
      let flag = true
      this.tableData.map(item=>{
        if (!item.isSelect) {
          flag = false
        }
      })
      this.isSelectAll = flag
      this.axios
        .post("/api/support_product_get_part", {
          type,
          basic_product_id: [this.$route.query.id],
          product_id,
          part_id: [],
        })
        .then((res) => {
          console.log(res);
          this.productPartList = res.data;
          this.productPartList.map((item) => (item.isSelect = false));
        });
      this.$forceUpdate();
    },
    handlePartClick(part, type) {
      // 部件单选
      this.productPartList.map((item) => (item.isSelect = false));
      part.isSelect = !part.isSelect;
      const temp_product = this.tableData.filter((item) => item.isSelect);
      const product_id = temp_product.map((item) => item.id);
      const temp_part = this.productPartList.filter((item) => item.isSelect);
      const part_id = temp_part.map((item) => item.id);
      this.axios
        .post("/api/support_product_get_part", {
          type,
          basic_product_id: [this.$route.query.id],
          product_id,
          part_id,
        })
        .then((res) => {
          console.log(res);
          this.changeableTableData = res.data;
        });
      this.$forceUpdate();
    },
    handleAddChangeable() {
      const temp = this.productPartList.filter((item) => item.isSelect);
      if (temp.length > 0) {
        this.changeableTableData.push({
          id: "",
          formula_h: "",
          formula_l: "",
          formula_w: "",
        });
      } else {
        this.$Message.warning("请选择部件名称");
      }
    },
    handleChangeableConfirm() {
      const temp_product = this.tableData.filter((item) => item.isSelect);
      const product_id = temp_product.map((item) => item.id);
      const temp_part = this.productPartList.filter((item) => item.isSelect);
      const part_id = temp_part.map((item) => item.id);
      this.axios
        .post("/api/support_product_batch", {
          type: 3,
          basic_product_id: [this.$route.query.id],
          product_id,
          part_id,
          change: this.changeableTableData,
        })
        .then((res) => {
          if (res.code == 200) {
            this.$Message.success(res.msg);
            this.tableData.map((item) => (item.isSelect = false));
            this.productPartList = [];
            this.changeableTableData = [];
            this.showModal = false;
          }
        });
    },
    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;
    },
    changePage(e) {
      this.pageIndex = e;
      this.proxyObj.page_index = this.pageIndex;
      this.getData(this.proxyObj);
    },
    changeSize(e) {
      this.pageSize = e;
      this.proxyObj.page_size = this.pageSize;
      this.getData(this.proxyObj);
    },
    goPage(n, row) {
      //n = 1 新增 2 编辑 3 查看
      let id = row ? row.id : "";
      this.$router.push({
        path: "/cms/product/edit",
        query: {
          type: n,
          id: id,
          back_id: this.$route.query.id,
          title: this.$route.query.title,
        },
      });
    },
    async exportData() {
      const res = await this.axios("/api/product_export", {
        params: { ...this.proxyObj },
      });
      if (res.code == 200) {
        let url = `${this.$store.state.ip}/api/storage/${res.data.file}`;
        location.href = url;
      }
    },
    uploadSuccess(res) {
      if (res.code == 200) {
        this.$Message.success(res.msg || "上传成功");
      } else {
        this.$Message.warning(res.msg || "上传失败");
      }
      this.getData(this.proxyObj);
    },
    uploadError(err) {
      this.$Message.error(err.msg || "上传失败");
    },
  },
};
</script>

<style lang="scss" scoped>
.show_modal_content {
  display: flex;
  .show_modal_content_left {
    width: 50%;
    min-height: 500px;
    overflow: hidden;
    overflow-y: auto;
    border-right: 1px solid #e8eaec;
    padding-top: 20px;
    .show_modal_content_left_item {
      width: 100%;
      display: flex;
      .show_modal_content_left_item_title,
      .show_modal_content_left_item_detail {
        margin-bottom: 10px;
        margin-right: 20px;
      }
      .show_modal_content_left_item_detail_warp {
        display: flex;
        justify-content: flex-start;
        align-items: flex-start;
        flex-wrap: wrap;
        .show_modal_content_left_item_detail {
        }
      }
    }
  }
  .show_modal_content_right {
    width: 50%;
    padding-left: 20px;
    .show_modal_content_right_top {
      display: flex;
      justify-content: flex-end;
      margin-top: 50px;
      margin-bottom: 10px;
    }
  }
}
</style>
