<template>
  <div class="BidSystemDeepeningOrderEdit">
    <Toptitle :title="type == 1 ? '深化单深化编辑' : '深化单深化详情'">
      <slot name="titleButton">
        <Button
          @click="goback()"
          type="primary"
          ghost
          style="margin-right: 10px"
          >返回</Button
        >
        <Button
          @click="postData()"
          type="primary"
          ghost
          v-show="type == 1"
          style="margin-right: 10px"
          >保存</Button
        >
      </slot>
    </Toptitle>
    <div class="top_search">
      <div><span>区域编码:</span>{{ formData.num }}</div>
      <div><span>区域名称:</span>{{ formData.area_title }}</div>
      <div><span>产品名称:</span>{{ formData.title }}</div>
      <div><span>数量:</span>{{ formData.num }}</div>
      <div><span>规格:</span>{{ formData.measure }}</div>
      <div><span>工艺属性:</span>{{ formData.process_property }}</div>
      <div><span>图号:</span>{{ formData.url_number }}</div>
      <div>
        <span>图纸:</span>
        <div>
          <span
            v-for="item in formData.url"
            :key="item"
            @click="checkImg(formData.url)"
          >
            <img :src="$store.state.ip + item" alt="" />
          </span>
        </div>
      </div>
      <div>
        <span>左右式:</span
        >{{
          formData.left_right_mode == 1
            ? "左式"
            : formData.left_right_mode == 2
            ? "右式"
            : "无"
        }}
      </div>
      <!-- <div><span>价格:</span>{{ formData.price }}</div> -->
      <div><span>备注:</span>{{ formData.remark }}</div>
    </div>
    <div class="table-data">
      <div class="table-data-btn">
        <span> </span>
        <div>
          <!-- <Upload style="display: inline"
                  name="your_file"
                  :show-upload-list="false"
                  :headers="headers"
                  :on-error="uploadError"
                  :on-success="uploadSuccess"
                  :action="$store.state.ip + '/api/upload_pic'">
            <Button type="primary"
                    :disabled="isCheck"
                    style="margin-right: 10px">导入</Button>
          </Upload> -->
          <Button
            type="primary"
            @click="handleAddList"
            v-show="type == 1"
            style="margin-right: 10px"
            >新增</Button
          >
        </div>
      </div>
      <div class="table-data-content">
        <!-- <vxe-table align="center"
                   border
                   resizable
                   show-overflow
                   :edit-config="{trigger: 'click', mode: 'cell'}"
                   :data="tableData">
          <vxe-table-column type="seq"
                            width="60"></vxe-table-column>
          <vxe-table-column field="house"
                            title="楼栋"
                            :edit-render="{name: 'input', attrs: {type: 'text', placeholder: '请输入'}}">
            <template #default="{ row }">
              <vxe-input v-model="row.house"
                         placeholder="请输入"></vxe-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="unit"
                            title="楼单元"
                            :edit-render="{name: 'input', attrs: {type: 'text', placeholder: '请输入'}}">
            <template #default="{ row }">
              <vxe-input v-model="row.unit"
                         placeholder="请输入"></vxe-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="layer"
                            title="楼层"
                            :edit-render="{name: 'input', attrs: {type: 'text', placeholder: '请输入'}}">
            <template #default="{ row }">
              <vxe-input v-model="row.layer"
                         placeholder="请输入"></vxe-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="number"
                            title="房间号"
                            :edit-render="{name: 'input', attrs: {type: 'text', placeholder: '请输入'}}">
            <template #default="{ row }">
              <vxe-input v-model="row.number"
                         placeholder="请输入"></vxe-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="title"
                            title="产品"
                            :edit-render="{name: 'input', attrs: {type: 'text', placeholder: '请输入'}}">
            <template #default="{ row }">
              <vxe-input v-model="row.title"
                         placeholder="请输入"></vxe-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="price"
                            title="价格"
                            :edit-render="{name: 'input', attrs: {type: 'text', placeholder: '请输入'}}">
            <template #default="{ row }">
              <vxe-input v-model="row.price"
                         placeholder="请输入"></vxe-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="product_unit"
                            title="计量单位"
                            :edit-render="{name: 'input', attrs: {type: 'text', placeholder: '请输入'}}">
            <template #default="{ row }">
              <vxe-input v-model="row.product_unit"
                         placeholder="请输入"></vxe-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="position"
                            title="位置"
                            :edit-render="{name: 'input', attrs: {type: 'text', placeholder: '请输入'}}">
            <template #default="{ row }">
              <vxe-input v-model="row.position"
                         placeholder="请输入"></vxe-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="url"
                            title="图纸"
                            :edit-render="{name: 'input', attrs: {type: 'text', placeholder: '请输入'}}">
            <template #default="{ row }">
              <vxe-input v-model="row.url"
                         placeholder="请输入"></vxe-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="url_number"
                            title="图号"
                            :edit-render="{name: 'input', attrs: {type: 'text', placeholder: '请输入'}}">
            <template #default="{ row }">
              <vxe-input v-model="row.url_number"
                         placeholder="请输入"></vxe-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="model"
                            title="型号"
                            :edit-render="{name: 'input', attrs: {type: 'text', placeholder: '请输入'}}">
            <template #default="{ row }">
              <vxe-input v-model="row.model"
                         placeholder="请输入"></vxe-input>
            </template>
          </vxe-table-column>
        </vxe-table> -->
        <Table :columns="tableColumns" :data="tableData" border>
          <template slot="houseSet" slot-scope="{ index }">
            <Input
              type="text"
              size="small"
              v-if="type == 1"
              v-model="tableData[index].house"
              placeholder="楼栋"
            />
            <span v-else>{{ tableData[index].house }}</span>
          </template>
          <template slot="unitSet" slot-scope="{ index }">
            <Input
              type="text"
              size="small"
              v-if="type == 1"
              v-model="tableData[index].unit"
              placeholder="单元"
            />
            <span v-else>{{ tableData[index].unit }}</span>
          </template>
          <template slot="layerSet" slot-scope="{ index }">
            <Input
              type="text"
              size="small"
              v-if="type == 1"
              v-model="tableData[index].layer"
              placeholder="楼层"
            />
            <span v-else>{{ tableData[index].layer }}</span>
          </template>
          <template slot="numberSet" slot-scope="{ index }">
            <Input
              type="text"
              size="small"
              :disabled="isCheck"
              v-if="type == 1"
              v-model="tableData[index].number"
              placeholder="房间号"
            />
            <span v-else>{{ tableData[index].number }}</span>
          </template>
          <template slot="type_titleSet" slot-scope="{ index }">
            <el-cascader
              v-if="type == 1"
              v-model="tableData[index].type_id"
              size="small"
              :show-all-levels="false"
              :options="cascader_list"
              :props="{
                expandTrigger: 'hover',
                children: 'child',
                value: 'id',
                label: 'title',
                emitPath: false,
                checkStrictly: true,
              }"
              @change="handleTypeTitleChange"
            ></el-cascader>
            <!-- @change="changeProduct(tableData[index], index)" -->
            <span v-else>{{ tableData[index].type_title }}</span>
          </template>
          <template slot="titleSet" slot-scope="{ index }">
            <Input
              type="text"
              size="small"
              :disabled="isCheck"
              v-if="type == 1"
              v-model="tableData[index].title"
              placeholder="产品"
            />
            <span v-else>{{ tableData[index].title }}</span>
          </template>
          <!-- <template slot="priceSet"
                    slot-scope="{ index }">
            <Input type="text"
                   size="small"
                   :disabled="isCheck"
                   v-model="tableData[index].price"
                   placeholder="价格" />
          </template> -->
          <template slot="product_unitSet" slot-scope="{ index }">
            <Input
              type="text"
              size="small"
              :disabled="isCheck"
              v-if="type == 1"
              v-model="tableData[index].product_unit"
              placeholder="单位"
            />
            <span v-else>{{ tableData[index].product_unit }}</span>
          </template>
          <template slot="positionSet" slot-scope="{ index }">
            <Input
              type="text"
              size="small"
              :disabled="isCheck"
              v-if="type == 1"
              v-model="tableData[index].position"
              placeholder="位置"
            />
            <span v-else>{{ tableData[index].position }}</span>
          </template>
          <template slot="urlSet" slot-scope="{ index }">
            <!-- <Input type="text"
                   size="small"
                   v-model="row.url"
                   placeholder="图纸" /> -->
            <div class="product-img">
              <div class="product-add">
                <div
                  class="items"
                  v-for="(_item, _index) of tableData[index].url"
                  :key="_index"
                >
                  <img
                    @click="looks(_item)"
                    v-for="(el, idx) in tableData[index].url"
                    :key="idx"
                    :src="$store.state.ip + el"
                    alt=""
                  />
                  <Icon
                    size="20"
                    v-show="type == 1"
                    @click="delItems(_index, tableData[index].url)"
                    class="delete-img"
                    type="ios-close-circle"
                  />
                </div>
                <div class="add-items" v-if="type == 1">
                  <div class="_item">
                    <Icon size="50" type="ios-add" />
                  </div>
                  <input
                    @change="changeIpt($event, tableData[index])"
                    type="file"
                    class="ipt"
                  />
                </div>
              </div>
            </div>
          </template>
          <template slot="url_numberSet" slot-scope="{ index }">
            <Input
              type="text"
              size="small"
              v-if="type == 1"
              v-model="tableData[index].url_number"
              placeholder="图号"
            />
            <span v-else>{{ tableData[index].url_number }}</span>
          </template>
          <template slot="modelSet" slot-scope="{ index }">
            <Input
              type="text"
              size="small"
              v-if="type == 1"
              v-model="tableData[index].model"
              placeholder="型号"
            />
            <span v-else>{{ tableData[index].model }}</span>
          </template>
          <template slot="set" slot-scope="{ index }">
            <a
              style="margin: 0 5px; color: red"
              v-show="type != 2"
              @click="handleSet(tableData[index], index)"
              >删除</a
            >
          </template>
          <div
            v-for="item in measureList"
            :key="item.e_title"
            :slot="'formula_' + item.e_title"
            slot-scope="{ index }"
          >
            <div>
              <Input
                v-if="type == 1"
                @on-focus="openKey(index, item.e_title)"
                size="small"
                clearable
                :placeholder="item.title"
                v-model="tableData[index][item.e_title]"
              />
              <span v-else>{{ tableData[index][item.e_title] }}</span>
            </div>
          </div>
          <!-- <div slot="formula_H"
               slot-scope="{ index }">
            <div>
              <Input :disabled="type == 2"
                     @on-focus="openKey(index, 'H')"
                     clearable
                     placeholder="高"
                     v-model="tableData[index].H"></Input>
            </div>
          </div> -->
          <!-- <template slot="formula_W"
                    slot-scope="{ index }">
            <div>
              <Input :disabled="type == 2"
                     @on-focus="openKey(index, 'W')"
                     clearable
                     placeholder="宽"
                     v-model="tableData[index].W"></Input>
            </div>
          </template> -->
          <!-- <template slot="formula_D"
                    slot-scope="{ index }">
            <div>
              <Input :disabled="type == 2"
                     @on-focus="openKey(index, 'D')"
                     clearable
                     placeholder="深"
                     v-model="tableData[index].D"></Input>
            </div>
          </template> -->
        </Table>
      </div>
    </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>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import KeyBoard from "../../../components/keyboard/index";
export default {
  name: "BidSystemDeepeningOrderEdit",
  components: {
    KeyBoard,
  },
  props: {},
  // import引入的组件需要注入到对象中才能使用
  data() {
    // 这里存放数据
    return {
      headers: { Authorization: localStorage.getItem("token") },
      formData: {},
      tableColumns: [
        {
          title: "序号",
          type: "index",
          align: "center",
          width: "80",
          resizable: true,
        },
        {
          title: "楼栋",
          key: "house",
          align: "center",
          width: "100",
          slot: "houseSet",
          resizable: true,
        },
        {
          title: "楼单元",
          key: "unit",
          align: "center",
          width: "100",
          slot: "unitSet",
          resizable: true,
        },
        {
          title: "楼层",
          key: "layer",
          align: "center",
          width: "100",
          slot: "layerSet",
          resizable: true,
        },
        {
          title: "房间号",
          key: "number",
          align: "center",
          width: "100",
          slot: "numberSet",
          resizable: true,
        },
        {
          title: "产品分类",
          key: "title",
          align: "center",
          minWidth: 200,
          slot: "type_titleSet",
          resizable: true,
        },
        {
          title: "产品",
          key: "title",
          align: "center",
          minWidth: 100,
          slot: "titleSet",
          resizable: true,
        },
        // {
        //   title: "价格",
        //   key: "price",
        //   align: "center",
        //   minWidth: 100,
        //   slot: "priceSet",
        // },
        {
          title: "计量单位",
          key: "product_unit",
          align: "center",
          minWidth: 100,
          slot: "product_unitSet",
          resizable: true,
        },
        {
          title: "位置",
          key: "position",
          align: "center",
          minWidth: 100,
          slot: "positionSet",
          resizable: true,
        },
        {
          title: "图纸",
          key: "url",
          align: "center",
          minWidth: 100,
          slot: "urlSet",
          resizable: true,
        },
        {
          title: "图号",
          key: "url_number",
          align: "center",
          minWidth: 120,
          slot: "url_numberSet",
          resizable: true,
        },
        {
          title: "型号",
          key: "model",
          align: "center",
          minWidth: 120,
          slot: "modelSet",
          resizable: true,
        },
        this.$route.query.type == 1
          ? {
              title: "操作",
              key: "set",
              align: "center",
              minWidth: 120,
              fixed: "right",
              slot: "set",
              resizable: true,
            }
          : { width: 1 },
      ],
      tableData: [],
      type: this.$route.query.type,
      isCheck: false,
      order_no: "",
      order_area_id: "",
      order_area_product_id: "",
      tempAddCol: [],
      measureList: [],
      showKey: false,
      cascader_list: [],
    };
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.type = this.$route.query.type;
    this.$route.query.type == 1
      ? (this.isCheck = false)
      : (this.isCheck = true);
    this.order_no = this.$route.query.order_no;
    this.order_area_id = this.$route.query.order_area_id;
    this.order_area_product_id = this.$route.query.order_area_product_id;
    // 获取产品分类
    this.axios.get("/api/basics_product_index").then((res) => {
      this.cascader_list = res.data.data;
    });
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.initData(
      this.order_no,
      this.order_area_id,
      this.order_area_product_id
    );
  },
  methods: {
    successKey(str) {
      // this.$nextTick(()=>{
      //   console.log(this.tableData[this.attrindex])
      //   this.tableData[this.attrindex][this.attrName] = str;
      // })
      let tableData = JSON.parse(JSON.stringify(this.tableData));
      tableData[this.attrindex][this.attrName] = str;
      this.tableData = tableData;
      this.showKey = false;
    },
    cancelKey() {
      this.showKey = false;
    },
    openKey(row, attr) {
      console.log(row, attr);
      this.showKey = true;
      this.attrindex = row;
      this.attrName = attr;
    },
    checkImg(item) {
      let list = [];
      item.forEach((el) => {
        list.push({ img_url: el });
      });
      // this.axios('/api/orders_img', { params: { id: this.order_area_product_id, type: 1 } }).then(res => {
      // if (res.code == 200) {
      this.$previewImg({
        list,
        baseUrl: this.$store.state.ip,
        baseImgField: "img_url",
        baseTitleField: "",
      });
      // }
      // })
    },
    handleUpLoad() {},
    handleAddList() {
      this.tableData.push({
        house: "",
        unit: "",
        layer: "",
        number: "",
        title: "",
        price: "",
        product_unit: "",
        position: "",
        url: [],
        url_number: "",
        model: "",
        type_id: this.formData.type_id,
        ...this.tempAddCol,
      });
      this.tableData.forEach((el, index) => {
        el.index = index + 1;
      });
    },
    initData(order_no, order_area_id, order_area_product_id) {
      this.axios({
        method: "get",
        url: "/api/order_area_product_list",
        params: {
          order_no,
          order_area_id,
          order_area_product_id,
        },
      }).then((res) => {
        this.formData = res.data;
        this.tableData = res.data.detail;
        this.tableData.forEach((el, index) => {
          el.index = index + 1;
          let tempM = el.measure.split("*");
          tempM.forEach((item) => {
            el[item.substring(0, 1)] = item.substring(1);
          });
          if (!el.type_id) {
            el.type_id = this.formData.type_id;
          }
        });
        let tempArr = [];
        this.measureList = res.data.measures;
        this.formData.measures.forEach((el, index) => {
          this.tempAddCol[el.e_title] = "";
          tempArr.push({
            title: el.title,
            key: el.e_title,
            align: "center",
            width: "150",
            slot: `formula_${el.e_title}`,
            resizable: true,
          });
        });
        this.tableColumns = [...this.tableColumns, ...tempArr];
      });
    },
    get_type_title(source, target) {
      return source.map((item) => {
        if (item.id == target.type_id) {
          return item.title;
        } else {
          return this.get_type_title(item.child, target);
        }
      });
    },
    goback() {
      this.$router.go(-1);
    },
    postData() {
      this.tableData.forEach((element) => {
        let measure = "";
        for (const key in element) {
          const el = element[key];
          this.formData.measures.forEach((item) => {
            if (key == item.e_title) {
              measure += `${item.e_title}${el}*`;
            }
          });
        }
        element.measure = measure.slice(0, measure.length - 1);
      });
      this.axios({
        method: "post",
        url: "/api/order_area_product_save",
        data: {
          order_no: this.order_no,
          order_area_id: this.order_area_id,
          order_area_product_id: this.order_area_product_id,
          list: this.tableData,
        },
      })
        .then((res) => {
          this.$Message.success(res.msg);
          this.goback();
        })
        .catch((err) => {});
    },
    uploadError(err) {
      this.$Message.error(err.msg || "上传失败");
    },
    //导入成功
    uploadSuccess(res) {
      if (res.code == 200) {
        this.$Message.success(res.msg || "上传成功");
        // const temp = res.data;
        // let list = [...this.postInfo.children, ...temp];
      } else {
        this.$Message.warning(res.msg || "上传失败");
      }
    },
    handleSet(row, index) {
      this.tableData.splice(index, 1);
      this.tableData.forEach((el, index) => {
        el.index = index + 1;
      });
    },
    looks(img) {
      const array = [{ img_url: img }];
      this.$previewImg({
        list: array,
        baseUrl: this.$store.state.ip,
        baseImgField: "img_url",
        baseTitleField: "",
      });
    },
    delItems(n, arr) {
      arr.splice(n, 1);
    },
    changeIpt(e, row) {
      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) => {
        row.url.push(res.data.url);
      });
    },
    handleTypeTitleChange(e){

    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {}, // 如果页面有keep-alive缓存功能，这个函数会触发
};
</script>

<style lang="scss" scoped>
.BidSystemDeepeningOrderEdit {
  position: relative;
  .top_search {
    width: 100%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-wrap: wrap;
    padding: 10px 0;
    span {
      min-width: 40px;
      margin-right: 5px;
    }
    div {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      width: 200px;
      word-break: break-word;
      padding: 10px;
      img {
        max-width: 60px;
      }
    }
  }
  .table-data {
    position: relative;
    width: 100%;
    .table-data-btn {
      display: flex;
      justify-content: space-between;
      padding: 10px 0;
    }
  }

  .product-img {
    padding-top: 10px;
  }
  .product-add {
    display: flex;
    flex-wrap: wrap;
    .ipt {
      position: absolute;
      width: 100%;
      height: 100%;
      opacity: 0;
      cursor: pointer;
      outline: none;
      top: 0;
      left: 0;
    }
    .add-items {
      width: 40px;
      height: 40px;
      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;
      }
    }
    .items {
      width: 40px;
      height: 40px;
      margin-bottom: 10px;
      display: flex;
      justify-content: center;
      align-items: center;
      background: #e7e7e7;
      margin-right: 10px;
      border-radius: 5px;
      position: relative;
      img {
        max-width: 40px;
        max-height: 40px;
      }
    }
  }
}
</style>
