<template>
  <div>
    <Toptitle
      :title="
        type == 1 ? '复制' : type == 2 ? '编辑' : type == 3 ? '查看' : '新增'
      "
    >
      <Button type="primary" style="margin-right:5px" ghost @click="back()"
        >取消</Button
      >
      <Button type="primary" v-show="type != 3" @click="handleSaveData"
        >保存</Button
      >
    </Toptitle>
    <div>
      <Row type="flex" justify="space-between" style="padding:10px 0">
        <Col span="4">
          <span>ID：</span>
          <span>
            <Input
              type="text"
              disabled
              style="width:80px"
              v-model="formData.id"
              placeholder="自动生成"
            />
          </span>
        </Col>
        <Col span="12" style="display:flex;align-items: center;">
          <span>工艺属性分类：</span>
          <span>
            <Select
              filterable
              filter-by-label
              v-model="formData.process_id"
              style="width: 100px;margin-right:5px"
              @on-change="handleProcessSelected"
            >
              <Option
                v-for="(item, index) in basic_process_list"
                :key="index"
                :label="item.title"
                :value="item.id"
              ></Option>
            </Select>
          </span>
          <span>
            <Select
              filterable
              filter-by-label
              @on-change="(e) => handleGetProcessIds(formData.process_id, e)"
              v-model="formData.type_title"
              style="width: 100px;margin-right:5px"
            >
              <Option
                v-for="(item, index) in type_title_list"
                :key="index"
                :label="item"
                :value="item"
              ></Option>
            </Select>
          </span>
          <span>
            <!-- <Select
              filterable
              filter-by-label
              multiple
              :max-tag-count="2"
              v-model="formData.process_ids"
              style="width: 300px"
            >
              <Option
                v-for="(item, index) in process_list"
                :key="index"
                :label="item.title"
                :value="item.id"
              ></Option>
            </Select> -->
            <el-select
              multiple
              collapse-tags
              filterable
              v-model="formData.process_ids"
              @change="changeProvinceSelect"
              style="width: 300px;height:32px"
              @remove-tag="removeProvinceTag"
            >
              <el-option
                label="全选"
                value="全选"
                v-show="process_list.length > 1"
                @click.native="selectProvinceAll"
              ></el-option>
              <el-option
                v-for="item in process_list"
                ref="options"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </span>
        </Col>
        <Col span="8">
          <span>部件名称：</span>
          <span>
            <Select
              filterable
              filter-by-label
              v-model="formData.part_id"
              @on-change="handlePartSelected"
              style="width: 200px"
            >
              <Option
                v-for="(item, index) in parts_list"
                :key="index"
                :label="item.title"
                :value="item.id"
              ></Option>
            </Select>
          </span>
        </Col>
      </Row>
      <Row
        type="flex"
        align="bottom"
        justify="space-between"
        style="padding-bottom:5px"
      >
        <Col><span>规则:</span> </Col>
        <Col>
          <Button
            size="small"
            type="primary"
            @click="handleSet({}, tableData.length, 1)"
            >新增规则</Button
          >
        </Col>
      </Row>
      <div>
        <Table
          :columns="tableColumns"
          border
          :max-height="500"
          :data="tableData"
        >
          <template slot="partDetailTitle" slot-scope="{ index }">
            <Select
              v-model="tableData[index].parts_detail_id"
              transfer
              @on-change="
                (e) => handlePartDetailSelected(tableData[index], index, e)
              "
            >
              <Option
                v-for="(item, index) in tableData[index].part_detail_list"
                :key="index"
                :label="item.spare_parts"
                :value="item.id"
              ></Option>
            </Select>
          </template>
          <template slot="measureSlot" slot-scope="{ index }">
            <Select v-model="tableData[index].basics_measure_id" transfer>
              <Option
                v-for="(item, index) in measure_list"
                :key="index"
                :label="item.title"
                :value="item.id"
              ></Option>
            </Select>
          </template>
          <template slot="numSlot" slot-scope="{ index }">
            <Input
              type="text"
              style="width:80px"
              v-model="tableData[index].num"
            />
          </template>
          <template slot="minSlot" slot-scope="{ index }">
            <Input
              type="text"
              style="width:80px"
              v-model="tableData[index].min"
            />
          </template>
          <template slot="maxSlot" slot-scope="{ index }">
            <Input
              type="text"
              style="width:80px"
              v-model="tableData[index].max"
            />
          </template>
          <template slot="materialDetailSlot" slot-scope="{ index }">
            <Select v-model="tableData[index].material_detail_id" transfer>
              <Option
                v-for="(item, index) in tableData[index].materialDetailList"
                :key="index"
                :label="item.materialDetailShow"
                :value="item.id"
              ></Option>
            </Select>
          </template>
          <template slot="setSlot" slot-scope="{ index }">
            <div>
              <a
                style="margin:0 5px;"
                @click="handleSet(tableData[index], index, 2)"
                >复制</a
              >
              <a
                style="margin:0 5px;"
                @click="handleSet(tableData[index], index, 3)"
                >删除</a
              >
            </div>
          </template>
        </Table>
      </div>
    </div>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';

export default {
  name: "",
  components: {},
  props: {},
  // import引入的组件需要注入到对象中才能使用
  data() {
    // 这里存放数据
    return {
      type: this.$route.query.type,
      id: this.$route.query.id,
      formData: {
        id: this.$route.query.id,
        process_id: "",
        part_id: "",
        type_title: "",
        process_ids: [],
      },
      urlSelectList: [],
      tableColumns: [
        {
          title: "零部件名称",
          align: "center",
          minWidth: 120,
          slot: "partDetailTitle",
        },
        {
          title: "物料名称",
          align: "center",
          minWidth: 100,
          key: "parts_detail_title",
        },
        {
          title: "测量字段",
          align: "center",
          minWidth: 100,
          slot: "measureSlot",
        },
        {
          title: "数量",
          align: "center",
          minWidth: 70,
          key: "num",
          slot: "numSlot",
        },
        {
          title: "最小数值(含)",
          align: "center",
          minWidth: 120,
          slot: "minSlot",
        },
        { title: "最大数值", align: "center", minWidth: 120, slot: "maxSlot" },
        {
          title: "物料规格",
          align: "center",
          minWidth: 100,
          key: "material_detail_id",
          slot: "materialDetailSlot",
        },
        { title: "操作", align: "center", minWidth: 120, slot: "setSlot" },
      ],
      tableData: [{}],
      basic_process_list: [], //工艺属性分类
      parts_list: [],
      type_title_list: [],
      process_list: [],
      measure_list: [],
    };
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.axios.get("/api/basics_properties_index").then((res) => {
      this.basic_process_list = res.data.data;
    });
    this.axios.get("/api/parts_index").then((res) => {
      this.parts_list = res.data.data;
    });
    this.axios.get("/api/basics_measure_index").then((res) => {
      this.measure_list = res.data.data;
    });
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.id && this.initData(this.id);
  },
  methods: {
    back() {
      this.$router.go(-1);
    },
    changeProvinceSelect(val) {
      if (!val.includes("全选") && val.length === this.process_list.length) {
        this.formData.process_ids.unshift("全选");
      } else if (
        val.includes("全选") &&
        val.length - 1 < this.process_list.length
      ) {
        this.formData.process_ids = this.formData.process_ids.filter((item) => {
          return item !== "全选";
        });
      }
    },
    removeProvinceTag(val) {
      if (val === "全选") {
        this.formData.process_ids = [];
      }
    },
    selectProvinceAll() {
      if (this.formData.process_ids.length <= this.process_list.length) {
        this.formData.process_ids = [];
        this.process_list.map((item) => {
          this.formData.process_ids.push(item.id);
        });
        this.formData.process_ids.unshift("全选");
      } else {
        this.formData.process_ids = [];
      }
    },
    handleSet(row, index, type) {
      if (!this.formData.part_id) {
        return this.$Message.warning("请先选择部件");
      }
      row.part_detail_list = JSON.parse(JSON.stringify(this.part_detail_list));
      row.part_id = this.formData.part_id;
      const obj = JSON.parse(JSON.stringify(row));
      switch (type) {
        case 1:
        case 2:
          this.tableData.splice(index, 0, obj);
          break;
        case 3:
          this.tableData.splice(index, 1);
          break;
      }
    },
    initData(id) {
      this.axios
        .get("/api/process_part_detail", { params: { id } })
        .then((res) => {
          this.formData = res.data.detail;
          this.formData.process_id = this.formData.bp_id;
          this.tableData = res.data.list;
          this.handleProcessSelected(res.data.detail.process_id);
          this.handleGetProcessIds(
            res.data.detail.process_id,
            res.data.detail.type_title
          );
          this.handlePartSelected(this.formData.part_id, 2);
        });
    },
    handleProcessSelected(p_id) {
      p_id &&
        this.axios.post("/api/process_sub_title", { p_id }).then((res) => {
          this.type_title_list = res.data;
        });
    },
    handleGetProcessIds(p_id, type_title) {
      this.axios
        .get("/api/properties_index", { params: { p_id, type_title } })
        .then((res) => {
          this.process_list = res.data.data;
        });
    },
    handlePartSelected(id, type) {
      id &&
        this.axios.get("/api/parts_detail", { params: { id } }).then((res) => {
          this.part_detail_list = res.data.detail;
          if (type == 2) {
            this.tableData.map((v, k) => {
              v.part_detail_list = JSON.parse(
                JSON.stringify(this.part_detail_list)
              );
              this.handlePartDetailSelected(v, k, v.parts_detail_id);
            });
          } else {
            this.tableData = [];
          }
          this.tableData = JSON.parse(JSON.stringify(this.tableData));
        });
    },
    handlePartDetailSelected(row, index, id) {
      if (id) {
        const material_id = row.part_detail_list.filter((v) => v.id == id)[0]
          .material_id;
        this.axios
          .get("/api/material", { params: { id: material_id } })
          .then((res) => {
            this.tableData[index].parts_detail_title = res.data[0].title;
            this.tableData[index].materialDetailList = res.data[0].detail.map(
              (v) => {
                return { id: v.id, materialDetailShow: v.long + "*" + v.width };
              }
            );
            this.tableData.splice(index, 1, this.tableData[index]);
          });
      }
    },
    handleSaveData() {
      if (this.type == 1) {
        this.formData.id = "";
      }
      this.axios
        .post("/api/process_part_edit", {
          ...this.formData,
          detail: this.tableData,
        })
        .then((res) => {
          if (res.code == 200) {
            this.$Message.success(res.msg);
            this.back();
          }
        });
    },
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {}, // 如果页面有keep-alive缓存功能，这个函数会触发
};
</script>

<style lang="scss" scoped>
/deep/.el-input__inner {
  height: 32px;
}
</style>
