<template>
  <Container>
    <!--    <div slot="tip" class="page-tip-div" style="margin-bottom: 0">-->
    <!--      <i class="el-icon-info"></i>-->
    <!--      温馨提示:-->
    <!--      <p>-->
    <!--        1、支持根据供货地区（如杭州仓、北京仓）、使用场景（如销售仓、售后仓）的不同创建不同仓库并进行进销存管理。-->
    <!--      </p>-->
    <!--      <p>-->
    <!--        2、仓库的状态-->
    <!--        除手工新建的仓库外，其他和商铺绑定的仓库随商铺状态变化而变化。-->
    <!--      </p>-->
    <!--      <p>-->
    <!--        3、仓库新建的时候是未始化状态,点【初始化】,输入【期初库存】,期初库存填写完毕的时候,点击初始化完成,这个时候仓库变更为正常状态,如果不用的时候调整为【停止】状态-->
    <!--      </p>-->
    <!--      <p>4、仓库在新建商铺时，系统会自动创建</p>-->
    <!--    </div>-->
    <div
      v-if="$accessCheck($Access.managementAddWarehouse)"
      slot="left"
      style="margin-top: 10px"
    >
      <el-button type="primary" size="small" @click="newWarehouse()">
        新建仓库
      </el-button>
    </div>
    <!-- 表格 -->
    <el-table :data="stock_list">
      <el-table-column prop="id" label="ID" width="50"></el-table-column>
      <el-table-column
        min-width="140"
        prop="warehouseCode"
        label="仓库编码"
      ></el-table-column>
      <el-table-column
        prop="warehouseName"
        label="仓库名称"
        min-width="140"
        :show-overflow-tooltip="true"
      ></el-table-column>
      <el-table-column
        prop="contactName"
        min-width="120"
        label="联系人"
      ></el-table-column>
      <el-table-column
        prop="contactMobile"
        min-width="120"
        label="联系方式"
      ></el-table-column>
      <el-table-column
        prop="address"
        min-width="160"
        label="仓库地址"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          {{ scope.row.area.provinceName }}-{{ scope.row.area.cityName }}-
          {{ scope.row.area.districtName }}- {{ scope.row.area.contactAddress }}
        </template>
      </el-table-column>
      <el-table-column min-width="100" prop="status" label="状态">
        <template slot-scope="scope">
          <el-switch
            v-if="$accessCheck($Access.managementEnableWarehouse)"
            v-model="scope.row.enableStatus"
            class="switchStyle"
            active-color="#36B365"
            :active-value="5"
            :inactive-value="4"
            active-text="启用"
            inactive-text="禁用"
            @change="openStock($event, scope.row)"
          ></el-switch>
          <div v-else>
            <span v-if="scope.row.enableStatus === 5" class="success-status">
              启用
            </span>
            <span v-else class="danger-status">禁用</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column width="180" fixed="right" label="操作">
        <template slot-scope="scope">
          <el-button-group class="table-btn-group">
            <el-button
              v-if="$accessCheck($Access.managementUpdateWarehouse)"
              type="text"
              @click="newWarehouse(scope.row.id)"
            >
              编辑
            </el-button>
            <el-button
              v-if="$accessCheck($Access.managementAddWarehouseBeginning)"
              :disabled="scope.row.beginningStatus === 4"
              type="text"
              @click="
                $router.push(
                  '/stock/WarehouseManagement/newStart?id=' + scope.row.id
                )
              "
            >
              {{ scope.row.beginningStatus === 4 ? "已初始" : "初始化" }}
            </el-button>
          </el-button-group>
          <!--                    <el-tooltip-->
          <!--                      v-if="$accessCheck($Access.managementDeleteWarehouse)"-->
          <!--                      content="删除"-->
          <!--                      placement="top"-->
          <!--                    >-->
          <!--                      <el-button-->
          <!--                        size="mini"-->
          <!--                        type="danger"-->
          <!--                        icon="el-icon-delete"-->
          <!--                        @click="delData(scope.row.id)"-->
          <!--                      ></el-button>-->
          <!--                    </el-tooltip>-->
        </template>
      </el-table-column>
    </el-table>
    <FooterPage
      :page-size="pre_page"
      :total-page.sync="total"
      :current-page.sync="page"
      @pageChange="pageChange"
      @sizeChange="sizeChange"
    ></FooterPage>
    <!--    新建仓库弹框-->
    <el-dialog
      :title="warehouse"
      :visible.sync="newWarehouse_flag"
      width="30%"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      @close="closeWarehouse('formData')"
    >
      <el-form
        ref="formData"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="仓库名称:" prop="warehouseName">
          <el-input
            v-model="formData.warehouseName"
            placeholder="请输入仓库名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="所属区域：" prop="provinceCode">
          <RegionSelect
            v-model="region"
            size="medium"
            style="width: 70%"
            @change="regionChange"
          />
        </el-form-item>
        <el-form-item label="详细地址：" prop="contactAddress">
          <el-input
            v-model="formData.contactAddress"
            placeholder="请输入详细地址"
          ></el-input>
        </el-form-item>
        <el-form-item label="联系人：" prop="contactName">
          <el-input
            v-model="formData.contactName"
            placeholder="请输入联系人"
          ></el-input>
        </el-form-item>
        <el-form-item label="联系方式：" prop="contactMobile">
          <el-input
            v-model="formData.contactMobile"
            placeholder="请输入联系方式"
          ></el-input>
        </el-form-item>
        <el-form-item label="成本算法" prop="costType">
          <el-select
            v-model="formData.costType"
            :disabled="!!stock_id"
            placeholder="请选择成本算法"
          >
            <el-option
              v-for="item in cost_algorithm"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>

          <el-tooltip effect="dark" placement="bottom-start">
            <div slot="content">
              <p>
                移动加权法：用于价格较为恒定的行业，每次进货的库存与金额会累加，进行成本重算
              </p>
              <p>个别计价法：用于价格波动较大的行业，按批次入库，分批次出库</p>
            </div>
            <i class="el-icon-warning-outline"></i>
          </el-tooltip>
          <div style="font-size: 12px; font-weight: normal; color: #e6a23c">
            温馨提示：成本算法一经设置不允许修改
          </div>
        </el-form-item>
        <!--          <el-form-item label="备注：">-->
        <!--            <el-input-->
        <!--              v-model="formData.remarks"-->
        <!--              type="textarea"-->
        <!--              :rows="3"-->
        <!--              style="width: 300px"-->
        <!--              placeholder="请输入备注"-->
        <!--            ></el-input>-->
        <!--          </el-form-item>-->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeWarehouse('formData')">取 消</el-button>
        <el-button type="primary" :loading="submit_loading" @click="onSubmit">
          确 定
        </el-button>
      </span>
    </el-dialog>
  </Container>
</template>

<script>
  import {
    getAllWarehouse,
    enableWarehouse,
    deleteWarehouse,
    updateWarehouse,
    addWarehouse,
    getWarehouseInfo,
  } from "@/api/Stock";
  import RegionSelect from "@/component/common/RegionSelectJSON";
  import { mapGetters } from "vuex";
  export default {
    name: "Management",
    components: {
      RegionSelect,
    },
    data() {
      return {
        cost_algorithm: [
          {
            label: "移动加权法",
            value: 1,
          },
          {
            label: "个别计价法",
            value: 2,
          },
        ],
        stock_status: "",
        stock_list: [],
        page: 1,
        pre_page: 12,
        total: 0,
        newWarehouse_flag: false,
        region: [],
        submit_loading: false,
        show_shop: false,
        formData: {
          costType: 1,
          shopName: "",
          warehouseCode: "",
          warehouseName: "",
          contactName: "",
          contactMobile: "",
          provinceCode: "",
          cityCode: "",
          districtCode: "",
          contactAddress: "",
          deleteStatus: 5,
          enableStatus: 5,
          remarks: "",
        },
        stock_id: "",
        rules: {
          warehouseName: [
            { required: true, message: "请输入仓库名称", trigger: "blur" },
          ],
          shopId: [
            { required: true, message: "请选择关联商铺", trigger: "change" },
          ],
          provinceCode: [
            { required: true, message: "请选择所属区域", trigger: "blur" },
          ],
          contactAddress: [
            { required: true, message: "请输入详细地址", trigger: "blur" },
          ],
          costType: [
            { required: true, message: "请选择成本算法", trigger: "change" },
          ],
          // contactName: [
          //   { required: true, message: "请输入联系人", trigger: "blur" },
          // ],
          // contactMobile: [
          //   { required: true, message: "请输入联系方式", trigger: "blur" },
          // ],
        },
        warehouse: "新建仓库",
      };
    },
    computed: {
      ...mapGetters({
        storeData: "MUser/storeData",
        systemType: "MUser/systemType",
      }),
    },
    created() {
      this.getData();
    },
    activated() {
      if (this.$_isInit()) return;
      this.getData();
    },
    methods: {
      async getData() {
        const { data, pageTotal } = await getAllWarehouse({
          page: this.page,
          pageSize: this.pre_page,
        });

        this.stock_list = data;
        this.total = pageTotal;
      },
      /** 分页切换 */
      pageChange(page) {
        this.page = page;
        this.getData();
      },
      /** 分页切换 */
      sizeChange(size) {
        this.pre_page = size;
        this.pageChange(1);
      },
      /** 状态筛选 启用或禁用 */
      statusChange() {
        this.pageChange(1);
      },
      /** 启用或禁用功能 */
      async openStock(val, row) {
        try {
          const data = await enableWarehouse({
            id: row.id,
            enableStatus: val,
          });
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        } catch (e) {
          await this.getData();
        }
      },
      delData(id) {
        this.$confirm("确定要删除该仓库吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(async () => {
          const data = await deleteWarehouse(id);

          this.$message({
            type: "success",
            message: "删除成功!",
          });
          await this.getData();
        });
      },
      // 新建仓库
      newWarehouse(id) {
        this.stock_id = "";
        if (id) {
          this.warehouse = "编辑仓库";
          this.stock_id = id;
          this.stockDetail();
        }
        this.newWarehouse_flag = true;
      },
      // 选择所属区域
      regionChange(val) {
        this.formData.provinceCode = val[0];
        this.formData.cityCode = val[1];
        this.formData.districtCode = val[2];
      },
      // 保存提交
      onSubmit() {
        if (
          !this.formData.warehouseName.trim() ||
          !this.region ||
          !this.formData.contactAddress.trim()
        ) {
          this.$message.warning("必填项不能为空");
          return;
        }
        this.$refs["formData"].validate(async (valid) => {
          if (valid) {
            this.submit_loading = true;
            let formData = this.formData;
            let target = {};
            if (this.stock_id) {
              target = await updateWarehouse(this.stock_id, formData);
            } else {
              target = await addWarehouse(formData);
            }
            const data = target;
            this.submit_loading = false;
            this.$message({
              message: "提交成功",
              type: "success",
            });
            await this.getData();
            this.closeWarehouse("formName");
          }
        });
      },
      /** 获取仓库详情 */
      async stockDetail() {
        const { data } = await getWarehouseInfo(this.stock_id);

        this.region = [data.provinceCode, data.cityCode, data.districtCode];
        this.formData = { ...data };
      },
      closeWarehouse(formData) {
        this.newWarehouse_flag = false;
        this.formData = {
          costType: 1,
        };
        this.region = [];
        this.$refs[formData].resetFields();
      },
    },
  };
</script>
<style scoped>
  .el-select,
  .el-input {
    width: 70%;
  }
</style>
