<template>
  <div>
    <Toptitle
      :title="
        type == 1
          ? '超标价格方案新增'
          : type == 2
          ? '超标价格方案编辑'
          : '超标价格方案详情'
      "
    >
      <slot name="titleButton">
        <Button @click="goBack" type="primary" ghost style="margin-right:10px;"
          >返回</Button
        >
        <Button
          @click="postData"
          type="primary"
          v-show="!isChecked"
          style="margin-right:10px;"
          >保存</Button
        >
      </slot>
    </Toptitle>
    <div class="top_search">
      <Form :model="formData" :label-width="100" class="top_search_form">
        <FormItem label="ID:">
          <Input
            type="text"
            size="small"
            disabled
            v-if="type != 3"
            v-model="formData.id"
            placeholder="自动生成"
            style="width: 200px"
          />
          <span v-else>{{ formData.id }}</span>
        </FormItem>
        <FormItem label="方案名称:">
          <Input
            type="text"
            size="small"
            v-if="type != 3"
            v-model="formData.title"
            placeholder="请输入方案名称"
            style="width: 200px"
          />
          <span v-else>{{ formData.title }}</span>
        </FormItem>
      </Form>
    </div>
    <div class="addBtn">
      <Button @click="handleRuleAdd()" v-show="!isChecked" type="primary"
        >新增规则</Button
      >
    </div>
    <Table :columns="tableColumns" max-height="600" :data="tableData" border>
      <template slot="productSet" slot-scope="{ index }">
        <!-- <Select v-model="tableData[index].basic_product_id"
                :disabled="isChecked"
                @on-change="changeProduct(tableData[index],index)">
          <Option v-for="item of cascader_list"
                  :key="item.id"
                  :value="item.id"
                  :label="item.title"></Option>
        </Select> -->
        <el-cascader
          v-if="type != 3"
          v-model="tableData[index].basic_product_id"
          size="small"
          :show-all-levels="false"
          :options="cascader_list"
          :props="{
            expandTrigger: 'hover',
            children: 'child',
            value: 'id',
            label: 'title',
            emitPath: false,
          }"
          @change="changeProduct(tableData[index], index)"
        ></el-cascader>
        <span v-else>{{ tableData[index].product_type_title }}</span>
      </template>
      <template slot="partsSet" slot-scope="{ index }">
        <Select v-model="tableData[index].part_id" v-if="type != 3">
          <!-- @on-change="changeProduct(tableData[index],index)" -->
          <Option
            v-for="item of tableData[index].partsList"
            :key="item.id"
            :value="item.id"
            :label="item.title"
          ></Option>
        </Select>
        <span v-else>{{ tableData[index].part_title }}</span>
      </template>
      <template slot="typeSet" slot-scope="{ index }">
        <Select v-model="tableData[index].type" v-if="type != 3">
          <!-- @on-change="changeProduct(tableData[index],index)" -->
          <Option label="高" :value="1"></Option>
          <Option label="宽" :value="2"></Option>
          <Option label="厚" :value="3"></Option>
        </Select>
        <span v-else>{{
          tableData[index].type == 1
            ? "高"
            : tableData[index].type == 2
            ? "宽"
            : "厚"
        }}</span>
      </template>
      <template slot="priceSet" slot-scope="{ index }">
        <Input
          @on-focus="openKey(index)"
          v-if="type != 3"
          clearable
          placeholder="请输入公式"
          v-model="tableData[index].formula"
        />
        <span v-else>{{ tableData[index].formula }}</span>
      </template>
      <template slot="set" slot-scope="{ index }">
        <a
          style="margin:0 5px"
          v-show="!isChecked"
          @click="handleSet(tableData[index], index, 4)"
          >删除</a
        >
      </template>
    </Table>
    <Modal
      v-model="keyModal"
      :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>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import KeyBoard from "../../../components/keyboard/index";

export default {
  name: "",
  components: { KeyBoard },
  props: {},
  // import引入的组件需要注入到对象中才能使用
  data() {
    // 这里存放数据
    return {
      type: this.$route.query.type || null,
      id: this.$route.query.id || null,
      isChecked: this.$route.query.type == 3,
      loading: false,
      tableData: [],
      page_index: 1,
      total: 0,
      page_size: 10,
      formData: {},
      keyModal: false,
      tableColumns: [
        {
          title: "产品分类",
          key: "basic_product_id",
          align: "center",
          minWidth: 140,
          slot: "productSet",
        },
        {
          title: "部件",
          key: "part_id",
          align: "center",
          minWidth: 140,
          slot: "partsSet",
        },
        {
          title: "测量字段",
          key: "type",
          align: "center",
          minWidth: 140,
          slot: "typeSet",
        },
        {
          title: "最小数值",
          key: "min",
          align: "center",
          minWidth: 160,
          render: (h, params) => {
            const { row, index } = params;
            const currencyRow = this.tableData[index];
            return this.type != 3
              ? h("Input", {
                  props: {
                    placeholder: "默认为0",
                    value: currencyRow.min,
                    disabled: this.isChecked,
                  },
                  on: {
                    "on-change": (e) => {
                      const val = e.target.value * 1;
                      currencyRow.min = val;
                      // this.tableData.splice(index, 1, currencyRow);
                    },
                  },
                })
              : h("span", {}, currencyRow.min);
          },
        },
        {
          title: "最大数值",
          key: "max",
          align: "center",
          minWidth: 160,
          render: (h, params) => {
            const { row, index } = params;
            const currencyRow = this.tableData[index];
            return this.type != 3
              ? h("Input", {
                  props: {
                    placeholder: "默认为99999",
                    value: currencyRow.max,
                    disabled: this.isChecked,
                  },
                  on: {
                    "on-change": (e) => {
                      const val = e.target.value * 1;
                      currencyRow.max = val;
                      // this.tableData.splice(index, 1, currencyRow);
                    },
                  },
                })
              : h("span", {}, currencyRow.max);
          },
        },
        {
          title: "超标价格",
          key: "formula",
          align: "center",
          slot: "priceSet",
          minWidth: 140,
        },
        { title: "操作", key: "", align: "center", slot: "set", width: 100 },
      ],
      partsList: [],
      measureList: [],
      attrindex: null,
      cascader_list: [],
    };
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    // 获取产品分类
    this.axios
      .get("/api/basics_product_index")
      .then((res) => {
        this.cascader_list = res.data.data;
      })
      .catch((err) => {
        console.error(err);
      });
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.id &&
        this.axios
          .get("/api/overdraft_detail", { params: { id: this.id } })
          .then((res) => {
            this.tableData = res.data.list;
            this.formData = res.data.detail;
            if (this.type != 3) {
              this.tableData.forEach((element, index) => {
                element.partsList = [];
                this.axios
                  .get("/api/get_part_by_basic_product", {
                    params: { basic_product_id: element.basic_product_id },
                  })
                  .then((res) => {
                    element.partsList = res.data;
                    this.tableData.splice(index, 1, element);
                    // this.$forceUpdate()
                  })
                  .catch((err) => {
                    console.error(err);
                  });
                element.basic_product_id &&
                  this.axios("/api/basics_product_list", {
                    params: { id: element.basic_product_id },
                  }).then((res) => {
                    if (res.code == 200) {
                      const { data } = res;
                      const result = data.filter(
                        (rows) => rows.id == element.basic_product_id
                      );
                      // this.productFiled = data;
                      this.measureList = result[0].measure;
                    }
                  });
              });
            }
          })
          .catch((err) => {
            console.error(err);
          });
    },
    goBack() {
      this.$router.go(-1);
    },
    handleSet(row, index, type) {
      this.tableData.splice(index, 1);
    },
    postData() {
      this.axios({
        method: "post",
        url: "/api/overdraft_edit",
        data: {
          ...this.formData,
          detail: this.tableData,
        },
      }).then((res) => {
        if (res.code == 200) {
          this.$Message.success(res.msg);
          this.goBack();
        }
      });
    },
    handleRuleAdd() {
      const obj = { min: null, max: null, formula: null };
      this.tableData.push(obj);
    },
    changeProduct(row, index) {
      row.basic_product_id &&
        this.axios
          .get("/api/get_part_by_basic_product", {
            params: { basic_product_id: row.basic_product_id },
          })
          .then((res) => {
            row.partsList = res.data;
            row.part_id = "";
            this.tableData.splice(index, 1, row);
          })
          .catch((err) => {
            console.error(err);
          });

      row.basic_product_id &&
        this.axios("/api/basics_product_list", {
          params: { id: row.basic_product_id },
        }).then((res) => {
          if (res.code == 200) {
            const { data } = res;
            const result = data.filter(
              (rows) => rows.id == row.basic_product_id
            );
            // this.productFiled = data;
            this.measureList = result[0].measure;
          }
        });
    },
    openKey(row) {
      this.keyModal = true;
      this.attrindex = row;
    },
    successKey(str) {
      this.tableData[this.attrindex].formula = str;
      this.keyModal = false;
      this.tableData.splice(this.attrindex, 1, this.tableData[this.attrindex]);
    },
    cancelKey() {
      this.keyModal = false;
    },
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {}, // 如果页面有keep-alive缓存功能，这个函数会触发
};
</script>

<style lang="scss" scoped>
.top_search {
  padding: 20px 0;
  width: 100%;
  .top_search_form {
    // width: 800px;
    // display: flex;
    // justify-content: space-around;
    /deep/ .ivu-form-item {
      display: inline-block;
      width: 300px;
    }
  }
}
.addBtn {
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
}
/deep/ .ivu-table-wrapper {
  overflow: visible;
}
/deep/.ivu-form-item-content {
  span {
    vertical-align: middle;
  }
}
</style>
