<template>
  <div class="page-container">
    <navFunction
      ref="navFunctionRef"
      module-title="云店"
      function-title="叫水码"
      :title="postForm.id ? '编辑' : '新增'"
      @change="$router.back()"
    ></navFunction>
    <el-row>
      <el-col :span="12" style="width:500px">
        <el-form
          ref="postForm"
          :model="postForm"
          :rules="postFormRule"
          label-width="80px"
          @keyup.enter.native="postFormSubmit()"
        >
          <template v-if="pageStatus === 'create'">
            <el-form-item label="运营中心" :prop="postForm.operationsCenterId" v-if="userInfo.userTypeModel == 'admin'">
              <el-select
                v-model="postForm.operationsCenterId"
                clearable
                filterable
                placeholder="请选择运营中心"
                @change="onOperationsCenterChange"
              >
                <el-option
                  v-for="item in operationsCenterList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="项目名称"
              :prop="postForm.orgId"
              v-if="userInfo.userTypeModel == 'admin' || userInfo.userTypeModel == 'operationsCenter'"
            >
              <el-select
                v-model="postForm.orgId"
                :disabled="!postForm.operationsCenterId"
                filterable
                clearable
                placeholder="请选择项目"
                @change="onProjectChange"
              >
                <el-option v-for="item in projectList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </template>
          <el-form-item label="房间号" prop="roomMarkId">
            <el-select
              v-model="postForm.roomMarkId"
              :disabled="!postForm.orgId || pageStatus === 'update'"
              filterable
              clearable
              placeholder="输入搜索选择房间号"
              @change="onSelectChange"
            >
              <el-option
                v-for="item in roomList"
                :key="item.roomMarkId"
                :label="item.roomName"
                :value="item.roomMarkId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="企业名称" prop="virtId">
            <el-select
              v-model="postForm.virtId"
              :disabled="!postForm.orgId"
              filterable
              clearable
              placeholder="输入搜索选择企业"
              @change="onSelect2Change"
            >
              <el-option v-for="item in virtList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="常驻人数" prop="residentNum">
            <number-input
              v-model="postForm.residentNum"
              maxlength="10"
              :value="postForm.residentNum"
              placeholder="请输入常驻人数"
            />
          </el-form-item>
          <el-form-item label="饮水数据" prop="historyInfo">
            <el-input
              maxlength="500"
              type="textarea"
              placeholder="请输入饮水数据"
              :rows="4"
              v-model="postForm.historyInfo"
            ></el-input>
            <div class="tips">
              原叫水品牌类型规格价格数量，逗号分隔，例如景田纯净水18.9L*16元*10，景田纯净水500ml24支装*30元*5
            </div>
          </el-form-item>
          <el-form-item label="叫水商品" prop="listMgtGoods">
            <el-table border :data="postForm.listMgtGoods">
              <el-table-column prop="productName" label="商品" width="200">
                <template slot-scope="{ row, $index }">
                  <template v-if="row.productName">
                    <div class="product">
                      <el-image
                        class="product-img"
                        v-if="row.listFile && row.listFile.length"
                        :src="row.listFile[0].fileUrl"
                      />
                      <div class="product-inner">
                        <div class="product-title">{{ row.productName }}</div>
                        <div class="product-desc">{{ row.descr }}</div>
                        <div class="product-price">{{ row.price }}元</div>
                      </div>
                    </div>
                  </template>
                  <template v-else>
                    <el-select
                      :value="row.productName"
                      filterable
                      remote
                      placeholder="输入商品名称搜索选择"
                      :remote-method="searchProduct"
                      :loading="searchProductLoading"
                      @change="onProductChange($event, $index)"
                    >
                      <el-option v-for="item in productList" :key="item.id" :label="item.productName" :value="item.id">
                      </el-option>
                    </el-select>
                  </template>
                </template>
              </el-table-column>
              <el-table-column prop="stock" label="数量">
                <template slot-scope="scope">
                  <number-input v-model="scope.row.quantity" :value="scope.row.quantity" :decimal="0" placeholder="请输入数量" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="77">
                <template slot-scope="scope">
                  <el-button size="mini" type="danger" @click="onMgtGoodDel(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="product-bottom" @click="onProductAdd" v-if="postForm.listMgtGoods.length < 10">
              继续添加+
            </div>
          </el-form-item>
          <el-form-item label="客户经理" prop="customerManagerId">
            <el-select
              v-model="postForm.customerManagerId"
              filterable
              clearable
              placeholder="输入用户名或姓名搜索选择"
              @change="onSelect3Change"
            >
              <el-option
                v-for="item in searchAccountManagerList"
                :key="item.id"
                :label="item.realName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="消费分润" prop="description">
            <number-input
              min="0"
              max="100"
              v-model="postForm.bonusProportion"
              :value="postForm.bonusProportion"
              placeholder="请输入消费分润"
            />
          </el-form-item>
        </el-form>
        <div class="dialog-footer tc db w-100">
          <el-button @click="$router.back()">取消</el-button>
          <el-button type="primary" :loading="postFormLoading" @click="postFormSubmit()">确定</el-button>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import API_FLASHDELIVER_JIAOSHUIMA from "@/api/flashdeliver/jiaoshuima";
import NumberInput from "@/components/NumberInput";

import {
  companyGetselectlist,
  organizationGetselectlist,
  organisationVirtualarchitectureList,
  getRoomInfo
} from "@/api/flashdeliver/jiaoshuima";

export default {
  components: { NumberInput },
  data() {
    return {
      postFormLoading: false,
      uploadUrl: this.axiosURL + `${process.env.BASE_API}/common/file/upload`, // 上传图片的地址
      postForm: {
        id: "",
        operationsCenterId: "",
        orgId: "",
        orgName: "",
        roomMarkId: "",
        roomInfo: "",
        virtId: "",
        virtName: "",
        merchantId: "",
        merchantName: "",
        residentNum: "",
        historyInfo: "",
        listMgtGoods: [],
        bonusProportion: "",
        customerManagerId: "",
        customerManagerName: ""
      },
      postFormRule: {
        roomMarkId: [{ required: true, message: "房间号不能为空", trigger: "change" }],
        virtId: [{ required: true, message: "企业不能为空", trigger: "change" }],
        listMgtGoods: [
          {
            required: true,
            type: "array",
            validator: (rule, value, callback) => {
              const listMgtGoods = value.filter(v => Boolean(v.productName));
              if (!listMgtGoods.length) {
                return callback(new Error("叫水商品不能为空"));
              }

              callback();
            },
            trigger: "change"
          }
        ]
      },
      operationsCenterList: [], // 运营中心列表
      projectList: [], // 项目列表
      virtList: [], // 企业列表
      roomList: [],
      productList: [],
      searchProductLoading: false,
      searchAccountManagerList: []
    };
  },
  computed: {
    userInfo() {
      return this.$store.getters.userInfo
    },
    pageStatus() {
      return this.$route.query.id ? "update" : "create";
    }
  },
  async created() {
    const { id } = this.$route.query;
    if (id) {
      this.postForm.id = id;
      this.queryDetail();
    } else {
      if (this.userInfo.userTypeModel == "project") {
        this.postForm.operationsCenterId = this.userInfo.companyId;
        this.postForm.orgId = this.userInfo.orgId;
      } else if (this.userInfo.userTypeModel == "operationsCenter") {
        this.postForm.operationsCenterId = this.userInfo.companyId;
        await this.getProjectList();
      } else {
        await this.getOperationsCenterList();
      }
      this.onProjectChange();
      this.onProductAdd();
      this.onProductAdd();
    }
  },
  methods: {
    queryDetail() {
      API_FLASHDELIVER_JIAOSHUIMA.query({
        roomMarkId: this.$route.query.roomMarkId
      }).then(res => {
        this.postForm = res.data;
        this.postForm.virtId = String(res.data.virtId);
        this.onProjectChange();
      });
    },
    getSelectField(value, listKey, valueKey = "value", labelKey = "label") {
      const ov = this[listKey].find(v => v[valueKey] === value);
      return ov ? ov[labelKey] : "";
    },
    postFormSubmit() {
      this.$refs["postForm"].validate(valid => {
        if (valid) {
          const params = {
            orgId: this.postForm.orgId,
            orgName: this.postForm.orgName,
            virtId: this.postForm.virtId,
            virtName: this.postForm.virtName,
            roomMarkId: this.postForm.roomMarkId,
            roomInfo: this.postForm.roomInfo,
            merchantId: this.postForm.merchantId,
            merchantName: this.postForm.merchantName,
            historyInfo: this.postForm.historyInfo,
            residentNum: Number(this.postForm.residentNum),
            listMgtGoods: this.postForm.listMgtGoods.filter(v => Boolean(v.productName)),
            customerManagerId: this.postForm.customerManagerId,
            customerManagerName: this.postForm.customerManagerName,
            bonusProportion: Number(this.postForm.bonusProportion)
          };

          this.pageStatus === "update" && (params.id = this.postForm.id);
          this.postFormLoading = true;
          // console.log("API_FLASHDELIVER_JIAOSHUIMA", this.pageStatus, params);
          // this.postFormLoading = false;

          API_FLASHDELIVER_JIAOSHUIMA[this.pageStatus](params)
            .then(res => {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.$router.back();
                }
              });
            })
            .finally(() => {
              this.postFormLoading = false;
            });
        }
      });
    },
    onProductChange(value, index) {
      const ov = this.productList.find(v => v.id === value);
      const listMgtGoods = this.postForm.listMgtGoods.filter(v => Boolean(v.productName));
      if (listMgtGoods.length && this.postForm.merchantId && ov.saleId !== this.postForm.merchantId) {
        this.$message.error("抱歉，不支持添加跨商户商品!");
        return;
      }
      this.postForm.merchantId = ov.saleId;
      this.postForm.merchantName = ov.saleName;
      this.postForm.listMgtGoods.splice(index, 1, {
        productId: ov.id,
        productName: ov.productName,
        listFile: ov.listFile,
        price: ov.price,
        descr: ov.descr,
        quantity: 1
      });
    },
    onMgtGoodDel(index) {
      if (this.postForm.listMgtGoods.length === 1) {
        this.postForm.merchantId = "";
        this.postForm.merchantName = "";
      }
      this.postForm.listMgtGoods.splice(index, 1);
    },
    onProductAdd() {
      this.postForm.listMgtGoods.push({
        productName: ""
      });
    },
    searchProduct(query) {
      if (query !== "") {
        this.searchProductLoading = true;
        API_FLASHDELIVER_JIAOSHUIMA.productList({
          pageNo: 1,
          pageSize: 999,
          operationsCenterId: this.postForm.operationsCenterId,
          projectId: this.postForm.orgId,
          productName: query,
          isProductSpec: 0,
          status: 2 // 已上架
        })
          .then(res => {
            this.productList = res.data;
          })
          .finally(() => {
            this.searchProductLoading = false;
          });
      } else {
        this.productList = [];
      }
    },
    // searchAccountManagerFun(query) {
    //   if (query !== "") {
    //     this.searchAccountManagerLoading = true;
    //     const params = {
    //       pageNo: 1,
    //       pageSize: 999,
    //       conditions: { keyword: query }
    //     };

    //     this.postForm.orgId && (params["conditions[orgId]"] = this.postForm.orgId);

    //     API_FLASHDELIVER_JIAOSHUIMA.queryAdminUser(params)
    //       .then(res => {
    //         this.searchAccountManagerList = res.data;
    //       })
    //       .finally(() => {
    //         this.searchAccountManagerLoading = false;
    //       });
    //   } else {
    //     this.searchAccountManagerList = [];
    //   }
    // },
    onSelectChange() {
      this.postForm["roomInfo"] = this.getSelectField(this.postForm.roomMarkId, "roomList", "roomMarkId", "roomName");
    },
    onSelect2Change() {
      this.postForm["virtName"] = this.getSelectField(this.postForm.virtId, "virtList");
    },
    onSelect3Change() {
      this.postForm["customerManagerName"] = this.getSelectField(
        this.postForm.customerManagerId,
        "searchAccountManagerList",
        "id",
        "realName"
      );
    },
    onOperationsCenterChange() {
      this.getProjectList();
    },
    onProjectChange() {
      this.postForm["orgName"] = this.getSelectField(this.postForm.orgId, "projectList");
      this.getVirtList();
      this.getRoomList();
      if (this.postForm.orgId) {
        this.getAccountMangerList();
      }
    },
    getAccountMangerList() {
      const params = {
        pageNo: 1,
        pageSize: 999,
        conditions: {
          orgId: this.postForm.orgId
          //  keyword: query
        }
      };

      API_FLASHDELIVER_JIAOSHUIMA.queryAdminUser(params).then(res => {
        this.searchAccountManagerList = res.data;
      });
    },
    getRoomList() {
      const params = {
        pageNo: 1,
        pageSize: 999,
        conditions: {
          orgId: this.postForm.orgId
          // queryRoomName: query || '',
        }
      };

      getRoomInfo(params).then(res => {
        this.roomList = res.data.data;
      });
    },
    async getVirtList() {
      const params = {
        pageNo: 1,
        pageSize: 999,
        conditions: {
          orgId: this.postForm.orgId
        }
      };

      organisationVirtualarchitectureList(params).then(res => {
        this.virtList = res.data;
      });
    },
    async getProjectList() {
      const params = {
        pageNo: 1,
        pageSize: 999
      };

      this.postForm.operationsCenterId && (params["conditions[companyId]"] = this.postForm.operationsCenterId);

      const res = await organizationGetselectlist(params);
      this.projectList = res.data;
      if (res.data && res.data.length === 1) {
        this.postForm.orgId = res.data[0].value;
      }
    },
    async getOperationsCenterList() {
      const res = await companyGetselectlist();
      this.operationsCenterList = res.data;
      if (res.data && res.data.length) {
        const operationsCenterId = res.data[0].value;
        this.postForm.operationsCenterId = operationsCenterId;
        this.getProjectList();
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.upload-image {
  box-sizing: border-box;
  width: 60px;
  height: 60px;
}

.upload-tip {
  font-size: 12px;
  color: #606266;
  margin-top: 7px;
}

.image-preview {
  position: relative;
  width: 60px;
  height: 60px;
  img {
    width: 100%;
    height: 100%;
  }
}
.image-preview-action {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  cursor: default;
  text-align: center;
  color: #fff;
  opacity: 0;
  font-size: 20px;
  background-color: rgba(0, 0, 0, 0.5);
  transition: opacity 0.3s;
  cursor: pointer;
  text-align: center;
  line-height: 200px;
  .el-icon-delete {
    font-size: 36px;
  }
}

.product-bottom {
  padding: 10px 0;
  text-align: center;
  font: 18px;
  font-weight: bold;
  color: #409eff;
  border-radius: 4px;
  cursor: pointer;
}

.product {
  display: flex;
  &-img {
    width: 60px;
    height: 60px;
    margin-right: 10px;
    border-radius: 4px;
  }
  &-inner {
    flex: 1;
    min-width: 0;
  }
  &-title {
    font-size: 14px;
    line-height: 20px;
    color: #333;
    overflow: hidden;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
    word-break: break-all;
    margin-bottom: 2px;
  }
  &-desc {
    color: #999;
    font-size: 12px;
    line-height: 18px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    margin-bottom: 2px;
  }
  &-price {
    color: #f56c6c;
  }
}

.tips {
  padding: 2px 0;
  font-size: 14px;
  line-height: 1.4;
  color: #999999;
  letter-spacing: 0;
  text-align: left;
}

.page-container .el-select {
  display: block;
}
</style>
